Compare commits

..

1 Commits

Author SHA1 Message Date
fiatjaf
aea4bf702e go jsr only and eliminate index.ts. 2026-01-27 23:59:55 -03:00
11 changed files with 50 additions and 545 deletions

1
.npmrc Normal file
View File

@@ -0,0 +1 @@
@jsr:registry=https://npm.jsr.io

View File

@@ -1,4 +1,4 @@
# [![JSR](https://jsr.io/badges/@nostr/tools)](https://jsr.io/@nostr/tools) @nostr/tools # ![](https://img.shields.io/github/actions/workflow/status/nbd-wtf/nostr-tools/test.yml) [![JSR](https://jsr.io/badges/@nostr/tools)](https://jsr.io/@nostr/tools) nostr-tools
Tools for developing [Nostr](https://github.com/fiatjaf/nostr) clients. Tools for developing [Nostr](https://github.com/fiatjaf/nostr) clients.
@@ -9,6 +9,9 @@ This package is only providing lower-level functionality. If you want higher-lev
## Installation ## Installation
```bash ```bash
# npm
npm install --save nostr-tools
# jsr # jsr
npx jsr add @nostr/tools npx jsr add @nostr/tools
``` ```
@@ -24,7 +27,7 @@ https://jsr.io/@nostr/tools/doc
### Generating a private key and a public key ### Generating a private key and a public key
```js ```js
import { generateSecretKey, getPublicKey } from '@nostr/tools/pure' import { generateSecretKey, getPublicKey } from 'nostr-tools/pure'
let sk = generateSecretKey() // `sk` is a Uint8Array let sk = generateSecretKey() // `sk` is a Uint8Array
let pk = getPublicKey(sk) // `pk` is a hex string let pk = getPublicKey(sk) // `pk` is a hex string
@@ -33,7 +36,7 @@ let pk = getPublicKey(sk) // `pk` is a hex string
To get the secret key in hex format, use To get the secret key in hex format, use
```js ```js
import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js' // already an installed dependency import { bytesToHex, hexToBytes } from '@noble/hashes/utils' // already an installed dependency
let skHex = bytesToHex(sk) let skHex = bytesToHex(sk)
let backToBytes = hexToBytes(skHex) let backToBytes = hexToBytes(skHex)
@@ -42,7 +45,7 @@ let backToBytes = hexToBytes(skHex)
### Creating, signing and verifying events ### Creating, signing and verifying events
```js ```js
import { finalizeEvent, verifyEvent } from '@nostr/tools/pure' import { finalizeEvent, verifyEvent } from 'nostr-tools/pure'
let event = finalizeEvent({ let event = finalizeEvent({
kind: 1, kind: 1,
@@ -59,8 +62,8 @@ let isGood = verifyEvent(event)
Doesn't matter what you do, you always should be using a `SimplePool`: Doesn't matter what you do, you always should be using a `SimplePool`:
```js ```js
import { finalizeEvent, generateSecretKey, getPublicKey } from '@nostr/tools/pure' import { finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools/pure'
import { SimplePool } from '@nostr/tools/pool' import { SimplePool } from 'nostr-tools/pool'
const pool = new SimplePool() const pool = new SimplePool()
@@ -123,8 +126,8 @@ relay.close()
To use this on Node.js you first must install `ws` and call something like this: To use this on Node.js you first must install `ws` and call something like this:
```js ```js
import { useWebSocketImplementation } from '@nostr/tools/pool' import { useWebSocketImplementation } from 'nostr-tools/pool'
// or import { useWebSocketImplementation } from '@nostr/tools/relay' if you're using the Relay directly // or import { useWebSocketImplementation } from 'nostr-tools/relay' if you're using the Relay directly
import WebSocket from 'ws' import WebSocket from 'ws'
useWebSocketImplementation(WebSocket) useWebSocketImplementation(WebSocket)
@@ -135,7 +138,7 @@ useWebSocketImplementation(WebSocket)
You can enable regular pings of connected relays with the `enablePing` option. This will set up a heartbeat that closes the websocket if it doesn't receive a response in time. Some platforms, like Node.js, don't report websocket disconnections due to network issues, and enabling this can increase the reliability of the `onclose` event. You can enable regular pings of connected relays with the `enablePing` option. This will set up a heartbeat that closes the websocket if it doesn't receive a response in time. Some platforms, like Node.js, don't report websocket disconnections due to network issues, and enabling this can increase the reliability of the `onclose` event.
```js ```js
import { SimplePool } from '@nostr/tools/pool' import { SimplePool } from 'nostr-tools/pool'
const pool = new SimplePool({ enablePing: true }) const pool = new SimplePool({ enablePing: true })
``` ```
@@ -145,7 +148,7 @@ const pool = new SimplePool({ enablePing: true })
You can also enable automatic reconnection with the `enableReconnect` option. This will make the pool try to reconnect to relays with an exponential backoff delay if the connection is lost unexpectedly. You can also enable automatic reconnection with the `enableReconnect` option. This will make the pool try to reconnect to relays with an exponential backoff delay if the connection is lost unexpectedly.
```js ```js
import { SimplePool } from '@nostr/tools/pool' import { SimplePool } from 'nostr-tools/pool'
const pool = new SimplePool({ enableReconnect: true }) const pool = new SimplePool({ enableReconnect: true })
``` ```
@@ -328,7 +331,7 @@ for (let profile of refs.profiles) {
### Querying profile data from a NIP-05 address ### Querying profile data from a NIP-05 address
```js ```js
import { queryProfile } from '@nostr/tools/nip05' import { queryProfile } from 'nostr-tools/nip05'
let profile = await queryProfile('jb55.com') let profile = await queryProfile('jb55.com')
console.log(profile.pubkey) console.log(profile.pubkey)
@@ -340,13 +343,13 @@ console.log(profile.relays)
To use this on Node.js < v18, you first must install `node-fetch@2` and call something like this: To use this on Node.js < v18, you first must install `node-fetch@2` and call something like this:
```js ```js
import { useFetchImplementation } from '@nostr/tools/nip05' import { useFetchImplementation } from 'nostr-tools/nip05'
useFetchImplementation(require('node-fetch')) useFetchImplementation(require('node-fetch'))
``` ```
### Including NIP-07 types ### Including NIP-07 types
```js ```js
import type { WindowNostr } from '@nostr/tools/nip07' import type { WindowNostr } from 'nostr-tools/nip07'
declare global { declare global {
interface Window { interface Window {
@@ -358,8 +361,8 @@ declare global {
### Encoding and decoding NIP-19 codes ### Encoding and decoding NIP-19 codes
```js ```js
import { generateSecretKey, getPublicKey } from '@nostr/tools/pure' import { generateSecretKey, getPublicKey } from 'nostr-tools/pure'
import * as nip19 from '@nostr/tools/nip19' import * as nip19 from 'nostr-tools/nip19'
let sk = generateSecretKey() let sk = generateSecretKey()
let nsec = nip19.nsecEncode(sk) let nsec = nip19.nsecEncode(sk)
@@ -387,7 +390,7 @@ assert(data.relays.length === 2)
[`nostr-wasm`](https://github.com/fiatjaf/nostr-wasm) is a thin wrapper over [libsecp256k1](https://github.com/bitcoin-core/secp256k1) compiled to WASM just for hashing, signing and verifying Nostr events. [`nostr-wasm`](https://github.com/fiatjaf/nostr-wasm) is a thin wrapper over [libsecp256k1](https://github.com/bitcoin-core/secp256k1) compiled to WASM just for hashing, signing and verifying Nostr events.
```js ```js
import { setNostrWasm, generateSecretKey, finalizeEvent, verifyEvent } from '@nostr/tools/wasm' import { setNostrWasm, generateSecretKey, finalizeEvent, verifyEvent } from 'nostr-tools/wasm'
import { initNostrWasm } from 'nostr-wasm' import { initNostrWasm } from 'nostr-wasm'
// make sure this promise resolves before your app starts calling finalizeEvent or verifyEvent // make sure this promise resolves before your app starts calling finalizeEvent or verifyEvent
@@ -400,9 +403,9 @@ initNostrWasm().then(setNostrWasm)
If you're going to use `Relay` and `SimplePool` you must also import `nostr-tools/abstract-relay` and/or `nostr-tools/abstract-pool` instead of the defaults and then instantiate them by passing the `verifyEvent`: If you're going to use `Relay` and `SimplePool` you must also import `nostr-tools/abstract-relay` and/or `nostr-tools/abstract-pool` instead of the defaults and then instantiate them by passing the `verifyEvent`:
```js ```js
import { setNostrWasm, verifyEvent } from '@nostr/tools/wasm' import { setNostrWasm, verifyEvent } from 'nostr-tools/wasm'
import { AbstractRelay } from '@nostr/tools/abstract-relay' import { AbstractRelay } from 'nostr-tools/abstract-relay'
import { AbstractSimplePool } from '@nostr/tools/abstract-pool' import { AbstractSimplePool } from 'nostr-tools/abstract-pool'
import { initNostrWasm } from 'nostr-wasm' import { initNostrWasm } from 'nostr-wasm'
initNostrWasm().then(setNostrWasm) initNostrWasm().then(setNostrWasm)
@@ -439,7 +442,7 @@ summary for relay read message and verify event
## Plumbing ## Plumbing
To develop `@nostr/tools`, install [`just`](https://just.systems/) and run `just -l` to see commands available. To develop `nostr-tools`, install [`just`](https://just.systems/) and run `just -l` to see commands available.
## License ## License

View File

@@ -11,7 +11,6 @@ import { normalizeURL } from './utils.ts'
import type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts' import type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'
import { type Filter } from './filter.ts' import { type Filter } from './filter.ts'
import { alwaysTrue } from './helpers.ts' import { alwaysTrue } from './helpers.ts'
import { Relay } from './relay.ts'
export type SubCloser = { close: (reason?: string) => void } export type SubCloser = { close: (reason?: string) => void }
@@ -20,16 +19,6 @@ export type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {
// in case that relay shouldn't be authenticated against // in case that relay shouldn't be authenticated against
// or a function to sign the AUTH event template otherwise (that function may still throw in case of failure) // or a function to sign the AUTH event template otherwise (that function may still throw in case of failure)
automaticallyAuth?: (relayURL: string) => null | ((event: EventTemplate) => Promise<VerifiedEvent>) automaticallyAuth?: (relayURL: string) => null | ((event: EventTemplate) => Promise<VerifiedEvent>)
// onRelayConnectionFailure is called with the URL of a relay that failed the initial connection
onRelayConnectionFailure?: (url: string) => void
// onRelayConnectionSuccess is called with the URL of a relay that succeeds the initial connection
onRelayConnectionSuccess?: (url: string) => void
// allowConnectingToRelay takes a relay URL and the operation being performed
// return false to skip connecting to that relay
allowConnectingToRelay?: (url: string, operation: ['read', Filter[]] | ['write', Event]) => boolean
// maxWaitForConnection takes a number in milliseconds that will be given to ensureRelay such that we
// don't get stuck forever when attempting to connect to a relay, it is 3000 (3 seconds) by default
maxWaitForConnection: number
} }
export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & { export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & {
@@ -51,10 +40,6 @@ export class AbstractSimplePool {
public enableReconnect: boolean public enableReconnect: boolean
public automaticallyAuth?: (relayURL: string) => null | ((event: EventTemplate) => Promise<VerifiedEvent>) public automaticallyAuth?: (relayURL: string) => null | ((event: EventTemplate) => Promise<VerifiedEvent>)
public trustedRelayURLs: Set<string> = new Set() public trustedRelayURLs: Set<string> = new Set()
public onRelayConnectionFailure?: (url: string) => void
public onRelayConnectionSuccess?: (url: string) => void
public allowConnectingToRelay?: (url: string, operation: ['read', Filter[]] | ['write', Event]) => boolean
public maxWaitForConnection: number
private _WebSocket?: typeof WebSocket private _WebSocket?: typeof WebSocket
@@ -64,10 +49,6 @@ export class AbstractSimplePool {
this.enablePing = opts.enablePing this.enablePing = opts.enablePing
this.enableReconnect = opts.enableReconnect || false this.enableReconnect = opts.enableReconnect || false
this.automaticallyAuth = opts.automaticallyAuth this.automaticallyAuth = opts.automaticallyAuth
this.onRelayConnectionFailure = opts.onRelayConnectionFailure
this.onRelayConnectionSuccess = opts.onRelayConnectionSuccess
this.allowConnectingToRelay = opts.allowConnectingToRelay
this.maxWaitForConnection = opts.maxWaitForConnection || 3000
} }
async ensureRelay( async ensureRelay(
@@ -200,28 +181,17 @@ export class AbstractSimplePool {
// open a subscription in all given relays // open a subscription in all given relays
const allOpened = Promise.all( const allOpened = Promise.all(
groupedRequests.map(async ({ url, filters }, i) => { groupedRequests.map(async ({ url, filters }, i) => {
if (this.allowConnectingToRelay?.(url, ['read', filters]) === false) {
handleClose(i, 'connection skipped by allowConnectingToRelay')
return
}
let relay: AbstractRelay let relay: AbstractRelay
try { try {
relay = await this.ensureRelay(url, { relay = await this.ensureRelay(url, {
connectionTimeout: connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1000) : undefined,
this.maxWaitForConnection < (params.maxWait || 0)
? Math.max(params.maxWait! * 0.8, params.maxWait! - 1000)
: this.maxWaitForConnection,
abort: params.abort, abort: params.abort,
}) })
} catch (err) { } catch (err) {
this.onRelayConnectionFailure?.(url)
handleClose(i, (err as any)?.message || String(err)) handleClose(i, (err as any)?.message || String(err))
return return
} }
this.onRelayConnectionSuccess?.(url)
let subscription = relay.subscribe(filters, { let subscription = relay.subscribe(filters, {
...params, ...params,
oneose: () => handleEose(i), oneose: () => handleEose(i),
@@ -328,11 +298,7 @@ export class AbstractSimplePool {
publish( publish(
relays: string[], relays: string[],
event: Event, event: Event,
params?: { options?: { onauth?: (evt: EventTemplate) => Promise<VerifiedEvent> },
onauth?: (evt: EventTemplate) => Promise<VerifiedEvent>
maxWait?: number
abort?: AbortSignal
},
): Promise<string>[] { ): Promise<string>[] {
return relays.map(normalizeURL).map(async (url, i, arr) => { return relays.map(normalizeURL).map(async (url, i, arr) => {
if (arr.indexOf(url) !== i) { if (arr.indexOf(url) !== i) {
@@ -340,29 +306,12 @@ export class AbstractSimplePool {
return Promise.reject('duplicate url') return Promise.reject('duplicate url')
} }
if (this.allowConnectingToRelay?.(url, ['write', event]) === false) { let r = await this.ensureRelay(url)
return Promise.reject('connection skipped by allowConnectingToRelay')
}
let r: Relay
try {
r = await this.ensureRelay(url, {
connectionTimeout:
this.maxWaitForConnection < (params?.maxWait || 0)
? Math.max(params!.maxWait! * 0.8, params!.maxWait! - 1000)
: this.maxWaitForConnection,
abort: params?.abort,
})
} catch (err) {
this.onRelayConnectionFailure?.(url)
return String('connection failure: ' + String(err))
}
return r return r
.publish(event) .publish(event)
.catch(async err => { .catch(async err => {
if (err instanceof Error && err.message.startsWith('auth-required: ') && params?.onauth) { if (err instanceof Error && err.message.startsWith('auth-required: ') && options?.onauth) {
await r.auth(params.onauth) await r.auth(options.onauth)
return r.publish(event) // retry return r.publish(event) // retry
} }
throw err throw err

View File

@@ -45,7 +45,7 @@ export class AbstractRelay {
private reconnectTimeoutHandle: ReturnType<typeof setTimeout> | undefined private reconnectTimeoutHandle: ReturnType<typeof setTimeout> | undefined
private pingIntervalHandle: ReturnType<typeof setInterval> | undefined private pingIntervalHandle: ReturnType<typeof setInterval> | undefined
private reconnectAttempts: number = 0 private reconnectAttempts: number = 0
private skipReconnection: boolean = false private closedIntentionally: boolean = false
private connectionPromise: Promise<void> | undefined private connectionPromise: Promise<void> | undefined
private openCountRequests = new Map<string, CountResolver>() private openCountRequests = new Map<string, CountResolver>()
@@ -120,9 +120,12 @@ export class AbstractRelay {
this._connected = false this._connected = false
this.connectionPromise = undefined this.connectionPromise = undefined
const wasIntentional = this.closedIntentionally
this.closedIntentionally = false // reset for next time
this.onclose?.() this.onclose?.()
if (this.enableReconnect && !this.skipReconnection) { if (this.enableReconnect && !wasIntentional) {
this.reconnect() this.reconnect()
} else { } else {
this.closeAllSubscriptions(reason) this.closeAllSubscriptions(reason)
@@ -136,15 +139,13 @@ export class AbstractRelay {
this.challenge = undefined this.challenge = undefined
this.authPromise = undefined this.authPromise = undefined
this.skipReconnection = false
this.connectionPromise = new Promise((resolve, reject) => { this.connectionPromise = new Promise((resolve, reject) => {
if (opts?.timeout) { if (opts?.timeout) {
connectionTimeoutHandle = setTimeout(() => { connectionTimeoutHandle = setTimeout(() => {
reject('connection timed out') reject('connection timed out')
this.connectionPromise = undefined this.connectionPromise = undefined
this.skipReconnection = true
this.onclose?.() this.onclose?.()
this.handleHardClose('relay connection timed out') this.closeAllSubscriptions('relay connection timed out')
}, opts.timeout) }, opts.timeout)
} }
@@ -190,13 +191,10 @@ export class AbstractRelay {
resolve() resolve()
} }
this.ws.onerror = () => { this.ws.onerror = ev => {
clearTimeout(connectionTimeoutHandle) clearTimeout(connectionTimeoutHandle)
reject('connection failed') reject((ev as any).message || 'websocket error')
this.connectionPromise = undefined this.handleHardClose('relay connection errored')
this.skipReconnection = true
this.onclose?.()
this.handleHardClose('relay connection failed')
} }
this.ws.onclose = ev => { this.ws.onclose = ev => {
@@ -468,7 +466,7 @@ export class AbstractRelay {
} }
public close() { public close() {
this.skipReconnection = true this.closedIntentionally = true
if (this.reconnectTimeoutHandle) { if (this.reconnectTimeoutHandle) {
clearTimeout(this.reconnectTimeoutHandle) clearTimeout(this.reconnectTimeoutHandle)
this.reconnectTimeoutHandle = undefined this.reconnectTimeoutHandle = undefined

View File

@@ -42,18 +42,3 @@ esbuild
console.log('cjs build success.') console.log('cjs build success.')
}) })
esbuild
.build({
...common,
entryPoints: ['index.ts'],
outfile: 'lib/nostr.bundle.js',
format: 'iife',
globalName: 'NostrTools',
define: {
window: 'self',
global: 'self',
process: '{"env": {}}',
},
})
.then(() => console.log('standalone build success.'))

View File

@@ -1,32 +0,0 @@
export * from './pure.ts'
export { Relay } from './relay.ts'
export * from './filter.ts'
export { SimplePool } from './pool.ts'
export * from './references.ts'
export * as nip04 from './nip04.ts'
export * as nip05 from './nip05.ts'
export * as nip10 from './nip10.ts'
export * as nip11 from './nip11.ts'
export * as nip13 from './nip13.ts'
export * as nip17 from './nip17.ts'
export * as nip18 from './nip18.ts'
export * as nip19 from './nip19.ts'
export * as nip21 from './nip21.ts'
export * as nip25 from './nip25.ts'
export * as nip27 from './nip27.ts'
export * as nip28 from './nip28.ts'
export * as nip30 from './nip30.ts'
export * as nip39 from './nip39.ts'
export * as nip42 from './nip42.ts'
export * as nip44 from './nip44.ts'
export * as nip47 from './nip47.ts'
export * as nip54 from './nip54.ts'
export * as nip57 from './nip57.ts'
export * as nip59 from './nip59.ts'
export * as nip77 from './nip77.ts'
export * as nip98 from './nip98.ts'
export * as kinds from './kinds.ts'
export * as fj from './fakejson.ts'
export * as utils from './utils.ts'

View File

@@ -1,8 +1,7 @@
{ {
"name": "@nostr/tools", "name": "@nostr/tools",
"version": "2.22.2", "version": "2.21.0",
"exports": { "exports": {
".": "./index.ts",
"./core": "./core.ts", "./core": "./core.ts",
"./pure": "./pure.ts", "./pure": "./pure.ts",
"./wasm": "./wasm.ts", "./wasm": "./wasm.ts",

View File

@@ -1,264 +1,14 @@
{ {
"type": "module", "type": "module",
"name": "nostr-tools",
"version": "2.22.2",
"description": "Tools for making a Nostr client.",
"repository": {
"type": "git",
"url": "https://github.com/nbd-wtf/nostr-tools.git"
},
"files": [
"lib"
],
"sideEffects": false,
"module": "./lib/esm/index.js",
"main": "./lib/cjs/index.js",
"types": "./lib/types/index.d.ts",
"exports": {
".": {
"import": "./lib/esm/index.js",
"require": "./lib/cjs/index.js",
"types": "./lib/types/index.d.ts"
},
"./core": {
"import": "./lib/esm/core.js",
"require": "./lib/cjs/core.js",
"types": "./lib/types/core.d.ts"
},
"./pure": {
"import": "./lib/esm/pure.js",
"require": "./lib/cjs/pure.js",
"types": "./lib/types/pure.d.ts"
},
"./wasm": {
"import": "./lib/esm/wasm.js",
"require": "./lib/cjs/wasm.js",
"types": "./lib/types/wasm.d.ts"
},
"./kinds": {
"import": "./lib/esm/kinds.js",
"require": "./lib/cjs/kinds.js",
"types": "./lib/types/kinds.d.ts"
},
"./filter": {
"import": "./lib/esm/filter.js",
"require": "./lib/cjs/filter.js",
"types": "./lib/types/filter.d.ts"
},
"./abstract-relay": {
"import": "./lib/esm/abstract-relay.js",
"require": "./lib/cjs/abstract-relay.js",
"types": "./lib/types/abstract-relay.d.ts"
},
"./relay": {
"import": "./lib/esm/relay.js",
"require": "./lib/cjs/relay.js",
"types": "./lib/types/relay.d.ts"
},
"./abstract-pool": {
"import": "./lib/esm/abstract-pool.js",
"require": "./lib/cjs/abstract-pool.js",
"types": "./lib/types/abstract-pool.d.ts"
},
"./pool": {
"import": "./lib/esm/pool.js",
"require": "./lib/cjs/pool.js",
"types": "./lib/types/pool.d.ts"
},
"./references": {
"import": "./lib/esm/references.js",
"require": "./lib/cjs/references.js",
"types": "./lib/types/references.d.ts"
},
"./nip04": {
"import": "./lib/esm/nip04.js",
"require": "./lib/cjs/nip04.js",
"types": "./lib/types/nip04.d.ts"
},
"./nip05": {
"import": "./lib/esm/nip05.js",
"require": "./lib/cjs/nip05.js",
"types": "./lib/types/nip05.d.ts"
},
"./nip06": {
"import": "./lib/esm/nip06.js",
"require": "./lib/cjs/nip06.js",
"types": "./lib/types/nip06.d.ts"
},
"./nip07": {
"types": "./lib/types/nip07.d.ts"
},
"./nip10": {
"import": "./lib/esm/nip10.js",
"require": "./lib/cjs/nip10.js",
"types": "./lib/types/nip10.d.ts"
},
"./nip11": {
"import": "./lib/esm/nip11.js",
"require": "./lib/cjs/nip11.js",
"types": "./lib/types/nip11.d.ts"
},
"./nip13": {
"import": "./lib/esm/nip13.js",
"require": "./lib/cjs/nip13.js",
"types": "./lib/types/nip13.d.ts"
},
"./nip17": {
"import": "./lib/esm/nip17.js",
"require": "./lib/cjs/nip17.js",
"types": "./lib/types/nip17.d.ts"
},
"./nip18": {
"import": "./lib/esm/nip18.js",
"require": "./lib/cjs/nip18.js",
"types": "./lib/types/nip18.d.ts"
},
"./nip19": {
"import": "./lib/esm/nip19.js",
"require": "./lib/cjs/nip19.js",
"types": "./lib/types/nip19.d.ts"
},
"./nip21": {
"import": "./lib/esm/nip21.js",
"require": "./lib/cjs/nip21.js",
"types": "./lib/types/nip21.d.ts"
},
"./nip25": {
"import": "./lib/esm/nip25.js",
"require": "./lib/cjs/nip25.js",
"types": "./lib/types/nip25.d.ts"
},
"./nip27": {
"import": "./lib/esm/nip27.js",
"require": "./lib/cjs/nip27.js",
"types": "./lib/types/nip27.d.ts"
},
"./nip28": {
"import": "./lib/esm/nip28.js",
"require": "./lib/cjs/nip28.js",
"types": "./lib/types/nip28.d.ts"
},
"./nip29": {
"import": "./lib/esm/nip29.js",
"require": "./lib/cjs/nip29.js",
"types": "./lib/types/nip29.d.ts"
},
"./nip30": {
"import": "./lib/esm/nip30.js",
"require": "./lib/cjs/nip30.js",
"types": "./lib/types/nip30.d.ts"
},
"./nip39": {
"import": "./lib/esm/nip39.js",
"require": "./lib/cjs/nip39.js",
"types": "./lib/types/nip39.d.ts"
},
"./nip42": {
"import": "./lib/esm/nip42.js",
"require": "./lib/cjs/nip42.js",
"types": "./lib/types/nip42.d.ts"
},
"./nip44": {
"import": "./lib/esm/nip44.js",
"require": "./lib/cjs/nip44.js",
"types": "./lib/types/nip44.d.ts"
},
"./nip46": {
"import": "./lib/esm/nip46.js",
"require": "./lib/cjs/nip46.js",
"types": "./lib/types/nip46.d.ts"
},
"./nip49": {
"import": "./lib/esm/nip49.js",
"require": "./lib/cjs/nip49.js",
"types": "./lib/types/nip49.d.ts"
},
"./nip54": {
"import": "./lib/esm/nip54.js",
"require": "./lib/cjs/nip54.js",
"types": "./lib/types/nip54.d.ts"
},
"./nip57": {
"import": "./lib/esm/nip57.js",
"require": "./lib/cjs/nip57.js",
"types": "./lib/types/nip57.d.ts"
},
"./nip59": {
"import": "./lib/esm/nip59.js",
"require": "./lib/cjs/nip59.js",
"types": "./lib/types/nip59.d.ts"
},
"./nip58": {
"import": "./lib/esm/nip58.js",
"require": "./lib/cjs/nip58.js",
"types": "./lib/types/nip58.d.ts"
},
"./nip75": {
"import": "./lib/esm/nip75.js",
"require": "./lib/cjs/nip75.js",
"types": "./lib/types/nip75.d.ts"
},
"./nip94": {
"import": "./lib/esm/nip94.js",
"require": "./lib/cjs/nip94.js",
"types": "./lib/types/nip94.d.ts"
},
"./nip98": {
"import": "./lib/esm/nip98.js",
"require": "./lib/cjs/nip98.js",
"types": "./lib/types/nip98.d.ts"
},
"./nip99": {
"import": "./lib/esm/nip99.js",
"require": "./lib/cjs/nip99.js",
"types": "./lib/types/nip99.d.ts"
},
"./nipb7": {
"import": "./lib/esm/nipb7.js",
"require": "./lib/cjs/nipb7.js",
"types": "./lib/types/nipb7.d.ts"
},
"./fakejson": {
"import": "./lib/esm/fakejson.js",
"require": "./lib/cjs/fakejson.js",
"types": "./lib/types/fakejson.d.ts"
},
"./signer": {
"import": "./lib/esm/signer.js",
"require": "./lib/cjs/signer.js",
"types": "./lib/types/signer.d.ts"
},
"./utils": {
"import": "./lib/esm/utils.js",
"require": "./lib/cjs/utils.js",
"types": "./lib/types/utils.d.ts"
}
},
"license": "Unlicense",
"dependencies": { "dependencies": {
"@noble/ciphers": "2.1.1", "@noble/ciphers": "npm:@jsr/noble__ciphers@2.1.1",
"@noble/curves": "2.0.1", "@noble/curves": "npm:@jsr/noble__curves@2.0.1",
"@noble/hashes": "2.0.1", "@noble/hashes": "npm:@jsr/noble__hashes@2.0.1",
"@scure/base": "2.0.0", "@scure/base": "npm:@jsr/scure__base@2.0.0",
"@scure/bip32": "2.0.1", "@scure/bip32": "npm:@jsr/scure__bip32@2.0.1",
"@scure/bip39": "2.0.1", "@scure/bip39": "npm:@jsr/scure__bip39@2.0.1",
"nostr-wasm": "0.1.0" "nostr-wasm": "0.1.0"
}, },
"peerDependencies": {
"typescript": ">=5.0.0"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
},
"keywords": [
"decentralization",
"social",
"censorship-resistance",
"client",
"nostr"
],
"devDependencies": { "devDependencies": {
"@types/node": "^18.13.0", "@types/node": "^18.13.0",
"@types/node-fetch": "^2.6.3", "@types/node-fetch": "^2.6.3",
@@ -274,8 +24,5 @@
"node-fetch": "^2.6.9", "node-fetch": "^2.6.9",
"prettier": "^3.0.3", "prettier": "^3.0.3",
"typescript": "^5.8.2" "typescript": "^5.8.2"
},
"scripts": {
"prepublish": "just build"
} }
} }

View File

@@ -15,7 +15,7 @@ export function useWebSocketImplementation(websocketImplementation: any) {
export class SimplePool extends AbstractSimplePool { export class SimplePool extends AbstractSimplePool {
constructor(options?: Pick<AbstractPoolConstructorOptions, 'enablePing' | 'enableReconnect'>) { constructor(options?: Pick<AbstractPoolConstructorOptions, 'enablePing' | 'enableReconnect'>) {
super({ verifyEvent, websocketImplementation: _WebSocket, maxWaitForConnection: 3000, ...options }) super({ verifyEvent, websocketImplementation: _WebSocket, ...options })
} }
} }

View File

@@ -6,7 +6,6 @@ import {
insertEventIntoDescendingList, insertEventIntoDescendingList,
binarySearch, binarySearch,
normalizeURL, normalizeURL,
mergeReverseSortedLists,
} from './utils.ts' } from './utils.ts'
import type { Event } from './core.ts' import type { Event } from './core.ts'
@@ -271,94 +270,6 @@ test('binary search', () => {
expect(binarySearch(['a', 'b', 'd', 'e'], b => ('[' < b ? -1 : '[' === b ? 0 : 1))).toEqual([0, false]) expect(binarySearch(['a', 'b', 'd', 'e'], b => ('[' < b ? -1 : '[' === b ? 0 : 1))).toEqual([0, false])
}) })
describe('mergeReverseSortedLists', () => {
test('merge empty lists', () => {
const list1: Event[] = []
const list2: Event[] = []
expect(mergeReverseSortedLists(list1, list2)).toHaveLength(0)
})
test('merge list with empty list', () => {
const list1 = [buildEvent({ id: 'a', created_at: 30 }), buildEvent({ id: 'b', created_at: 20 })]
const list2: Event[] = []
const result = mergeReverseSortedLists(list1, list2)
expect(result).toHaveLength(2)
expect(result.map(e => e.id)).toEqual(['a', 'b'])
})
test('merge two simple lists', () => {
const list1 = [
buildEvent({ id: 'a', created_at: 30 }),
buildEvent({ id: 'b', created_at: 10 }),
buildEvent({ id: 'f', created_at: 3 }),
buildEvent({ id: 'g', created_at: 2 }),
]
const list2 = [
buildEvent({ id: 'c', created_at: 25 }),
buildEvent({ id: 'd', created_at: 5 }),
buildEvent({ id: 'e', created_at: 1 }),
]
const result = mergeReverseSortedLists(list1, list2)
expect(result.map(e => e.id)).toEqual(['a', 'c', 'b', 'd', 'f', 'g', 'e'])
})
test('merge lists with same timestamps', () => {
const list1 = [
buildEvent({ id: 'a', created_at: 30 }),
buildEvent({ id: 'b', created_at: 20 }),
buildEvent({ id: 'f', created_at: 10 }),
]
const list2 = [
buildEvent({ id: 'c', created_at: 30 }),
buildEvent({ id: 'd', created_at: 20 }),
buildEvent({ id: 'e', created_at: 20 }),
]
const result = mergeReverseSortedLists(list1, list2)
expect(result.map(e => e.id)).toEqual(['c', 'a', 'd', 'e', 'b', 'f'])
})
test('deduplicate events with same timestamp and id', () => {
const list1 = [
buildEvent({ id: 'a', created_at: 30 }),
buildEvent({ id: 'b', created_at: 20 }),
buildEvent({ id: 'b', created_at: 20 }),
buildEvent({ id: 'c', created_at: 20 }),
buildEvent({ id: 'd', created_at: 10 }),
]
const list2 = [
buildEvent({ id: 'a', created_at: 30 }),
buildEvent({ id: 'c', created_at: 20 }),
buildEvent({ id: 'b', created_at: 20 }),
buildEvent({ id: 'd', created_at: 10 }),
buildEvent({ id: 'e', created_at: 10 }),
buildEvent({ id: 'd', created_at: 10 }),
]
console.log('==================')
const result = mergeReverseSortedLists(list1, list2)
console.log(
'result:',
result.map(e => e.id),
)
expect(result.map(e => e.id)).toEqual(['a', 'c', 'b', 'd', 'e'])
})
test('merge when one list is completely before the other', () => {
const list1 = [buildEvent({ id: 'a', created_at: 50 }), buildEvent({ id: 'b', created_at: 40 })]
const list2 = [buildEvent({ id: 'c', created_at: 30 }), buildEvent({ id: 'd', created_at: 20 })]
const result = mergeReverseSortedLists(list1, list2)
expect(result).toHaveLength(4)
expect(result.map(e => e.id)).toEqual(['a', 'b', 'c', 'd'])
})
test('merge when one list is completely after the other', () => {
const list1 = [buildEvent({ id: 'a', created_at: 10 }), buildEvent({ id: 'b', created_at: 5 })]
const list2 = [buildEvent({ id: 'c', created_at: 30 }), buildEvent({ id: 'd', created_at: 20 })]
const result = mergeReverseSortedLists(list1, list2)
expect(result).toHaveLength(4)
expect(result.map(e => e.id)).toEqual(['c', 'd', 'a', 'b'])
})
})
describe('normalizeURL', () => { describe('normalizeURL', () => {
test('normalizes wss:// URLs', () => { test('normalizes wss:// URLs', () => {
expect(normalizeURL('wss://example.com')).toBe('wss://example.com/') expect(normalizeURL('wss://example.com')).toBe('wss://example.com/')

View File

@@ -1,4 +1,4 @@
import type { NostrEvent } from './core.ts' import type { Event } from './core.ts'
export const utf8Decoder: TextDecoder = new TextDecoder('utf-8') export const utf8Decoder: TextDecoder = new TextDecoder('utf-8')
export const utf8Encoder: TextEncoder = new TextEncoder() export const utf8Encoder: TextEncoder = new TextEncoder()
@@ -22,7 +22,7 @@ export function normalizeURL(url: string): string {
} }
} }
export function insertEventIntoDescendingList(sortedArray: NostrEvent[], event: NostrEvent): NostrEvent[] { export function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {
const [idx, found] = binarySearch(sortedArray, b => { const [idx, found] = binarySearch(sortedArray, b => {
if (event.id === b.id) return 0 if (event.id === b.id) return 0
if (event.created_at === b.created_at) return -1 if (event.created_at === b.created_at) return -1
@@ -34,7 +34,7 @@ export function insertEventIntoDescendingList(sortedArray: NostrEvent[], event:
return sortedArray return sortedArray
} }
export function insertEventIntoAscendingList(sortedArray: NostrEvent[], event: NostrEvent): NostrEvent[] { export function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {
const [idx, found] = binarySearch(sortedArray, b => { const [idx, found] = binarySearch(sortedArray, b => {
if (event.id === b.id) return 0 if (event.id === b.id) return 0
if (event.created_at === b.created_at) return -1 if (event.created_at === b.created_at) return -1
@@ -68,62 +68,6 @@ export function binarySearch<T>(arr: T[], compare: (b: T) => number): [number, b
return [start, false] return [start, false]
} }
export function mergeReverseSortedLists(list1: NostrEvent[], list2: NostrEvent[]): NostrEvent[] {
const result: NostrEvent[] = new Array(list1.length + list2.length)
result.length = 0
let i1 = 0
let i2 = 0
let sameTimestampIds: string[] = []
while (i1 < list1.length && i2 < list2.length) {
let next: NostrEvent
if (list1[i1]?.created_at > list2[i2]?.created_at) {
next = list1[i1]
i1++
} else {
next = list2[i2]
i2++
}
if (result.length > 0 && result[result.length - 1].created_at === next.created_at) {
if (sameTimestampIds.includes(next.id)) continue
} else {
sameTimestampIds.length = 0
}
result.push(next)
sameTimestampIds.push(next.id)
}
while (i1 < list1.length) {
const next = list1[i1]
i1++
if (result.length > 0 && result[result.length - 1].created_at === next.created_at) {
if (sameTimestampIds.includes(next.id)) continue
} else {
sameTimestampIds.length = 0
}
result.push(next)
sameTimestampIds.push(next.id)
}
while (i2 < list2.length) {
const next = list2[i2]
i2++
if (result.length > 0 && result[result.length - 1].created_at === next.created_at) {
if (sameTimestampIds.includes(next.id)) continue
} else {
sameTimestampIds.length = 0
}
result.push(next)
sameTimestampIds.push(next.id)
}
return result
}
export class QueueNode<V> { export class QueueNode<V> {
public value: V public value: V
public next: QueueNode<V> | null = null public next: QueueNode<V> | null = null