Remove CustomEvent

This commit is contained in:
Jon Staab
2024-08-19 08:59:39 -07:00
parent 975d51cafa
commit 8d3ca2ef6a
25 changed files with 124 additions and 120 deletions
+1 -4
View File
@@ -1,10 +1,7 @@
#!/bin/bash #!/bin/bash
for package in $(./get_packages.py); do for package in $(./get_packages.py); do
tag=$(git describe --tags --abbrev=0 --match=$package'/*') if [ $(./show_changes.sh $package | wc -l) -gt 0 ]; then
changes=$(git diff "$tag" "packages/$package" | wc -l)
if [ $changes -gt 0 ]; then
echo $package echo $package
fi fi
done done
+5 -5
View File
@@ -1,12 +1,12 @@
import {hexToBytes} from '@noble/hashes/utils' import {hexToBytes} from '@noble/hashes/utils'
import {getPublicKey, finalizeEvent} from 'nostr-tools' import {getPublicKey, finalizeEvent} from 'nostr-tools'
import {now} from '@welshman/lib' import {now} from '@welshman/lib'
import type {CustomEvent, EventTemplate, Filter} from '@welshman/util' import type {TrustedEvent, StampedEvent, Filter} from '@welshman/util'
import {subscribe, publish} from '@welshman/net' import {subscribe, publish} from '@welshman/net'
export type DVMHandler = { export type DVMHandler = {
stop?: () => void stop?: () => void
handleEvent: (e: CustomEvent) => AsyncGenerator<EventTemplate> handleEvent: (e: TrustedEvent) => AsyncGenerator<StampedEvent>
} }
export type CreateDVMHandler = (dvm: DVM) => DVMHandler export type CreateDVMHandler = (dvm: DVM) => DVMHandler
@@ -49,7 +49,7 @@ export class DVM {
const filters = [filter] const filters = [filter]
const sub = subscribe({relays, filters}) const sub = subscribe({relays, filters})
sub.emitter.on('event', (url: string, e: CustomEvent) => this.onEvent(e)) sub.emitter.on('event', (url: string, e: TrustedEvent) => this.onEvent(e))
sub.emitter.on('complete', () => resolve()) sub.emitter.on('complete', () => resolve())
}) })
} }
@@ -63,7 +63,7 @@ export class DVM {
this.active = false this.active = false
} }
async onEvent(request: CustomEvent) { async onEvent(request: TrustedEvent) {
const {expireAfter = 60 * 60} = this.opts const {expireAfter = 60 * 60} = this.opts
if (this.seen.has(request.id)) { if (this.seen.has(request.id)) {
@@ -108,7 +108,7 @@ export class DVM {
} }
} }
async publish(template: EventTemplate) { async publish(template: StampedEvent) {
const {sk, relays} = this.opts const {sk, relays} = this.opts
const event = finalizeEvent(template, hexToBytes(sk)) const event = finalizeEvent(template, hexToBytes(sk))
+2 -2
View File
@@ -1,5 +1,5 @@
import {Emitter, now} from '@welshman/lib' import {Emitter, now} from '@welshman/lib'
import type {CustomEvent, SignedEvent} from '@welshman/util' import type {TrustedEvent, SignedEvent} from '@welshman/util'
import {subscribe, publish} from '@welshman/net' import {subscribe, publish} from '@welshman/net'
import type {Subscription, Publish} from '@welshman/net' import type {Subscription, Publish} from '@welshman/net'
@@ -32,7 +32,7 @@ export const makeDvmRequest = (request: DVMRequestOptions) => {
const sub = subscribe({relays, timeout, filters}) const sub = subscribe({relays, timeout, filters})
const pub = publish({event, relays, timeout}) const pub = publish({event, relays, timeout})
sub.emitter.on('event', (url: string, event: CustomEvent) => { sub.emitter.on('event', (url: string, event: TrustedEvent) => {
if (event.kind === 7000) { if (event.kind === 7000) {
emitter.emit(DVMEvent.Progress, url, event) emitter.emit(DVMEvent.Progress, url, event)
} else { } else {
+6 -6
View File
@@ -1,5 +1,5 @@
import {uniq, identity, flatten, pushToMapKey, intersection, tryCatch, now} from '@welshman/lib' import {uniq, identity, flatten, pushToMapKey, intersection, tryCatch, now} from '@welshman/lib'
import type {CustomEvent, Filter} from '@welshman/util' import type {TrustedEvent, Filter} from '@welshman/util'
import {Tags, intersectFilters, matchFilter, getAddress, getIdFilters, unionFilters} from '@welshman/util' import {Tags, intersectFilters, matchFilter, getAddress, getIdFilters, unionFilters} from '@welshman/util'
import type {CreatedAtItem, RequestItem, ListItem, LabelItem, WOTItem, DVMItem, Scope, Feed, FeedOptions} from './core' import type {CreatedAtItem, RequestItem, ListItem, LabelItem, WOTItem, DVMItem, Scope, Feed, FeedOptions} from './core'
import {getFeedArgs, feedsFromTags} from './utils' import {getFeedArgs, feedsFromTags} from './utils'
@@ -109,7 +109,7 @@ export class FeedCompiler {
items.map(({mappings, ...request}) => items.map(({mappings, ...request}) =>
this.options.requestDVM({ this.options.requestDVM({
...request, ...request,
onEvent: async (e: CustomEvent) => { onEvent: async (e: TrustedEvent) => {
const tags = Tags.wrap(await tryCatch(() => JSON.parse(e.content)) || []) const tags = Tags.wrap(await tryCatch(() => JSON.parse(e.content)) || [])
for (const feed of feedsFromTags(tags, mappings)) { for (const feed of feedsFromTags(tags, mappings)) {
@@ -215,11 +215,11 @@ export class FeedCompiler {
async _compileLists(listItems: ListItem[]): Promise<RequestItem[]> { async _compileLists(listItems: ListItem[]): Promise<RequestItem[]> {
const addresses = uniq(listItems.flatMap(({addresses}) => addresses)) const addresses = uniq(listItems.flatMap(({addresses}) => addresses))
const eventsByAddress = new Map<string, CustomEvent>() const eventsByAddress = new Map<string, TrustedEvent>()
await this.options.request({ await this.options.request({
filters: getIdFilters(addresses), filters: getIdFilters(addresses),
onEvent: (e: CustomEvent) => eventsByAddress.set(getAddress(e), e), onEvent: (e: TrustedEvent) => eventsByAddress.set(getAddress(e), e),
}) })
const feeds = flatten( const feeds = flatten(
@@ -246,14 +246,14 @@ export class FeedCompiler {
} }
async _compileLabels(labelItems: LabelItem[]): Promise<RequestItem[]> { async _compileLabels(labelItems: LabelItem[]): Promise<RequestItem[]> {
const events: CustomEvent[] = [] const events: TrustedEvent[] = []
await Promise.all( await Promise.all(
labelItems.map(({mappings, relays, ...filter}) => labelItems.map(({mappings, relays, ...filter}) =>
this.options.request({ this.options.request({
relays, relays,
filters: [{kinds: [1985], ...filter}], filters: [{kinds: [1985], ...filter}],
onEvent: (e: CustomEvent) => events.push(e), onEvent: (e: TrustedEvent) => events.push(e),
}) })
) )
) )
+3 -3
View File
@@ -1,4 +1,4 @@
import type {CustomEvent, Filter} from '@welshman/util' import type {TrustedEvent, Filter} from '@welshman/util'
export enum FeedType { export enum FeedType {
Address = "address", Address = "address",
@@ -110,7 +110,7 @@ export type RequestItem = {
} }
export type RequestOpts = RequestItem & { export type RequestOpts = RequestItem & {
onEvent: (event: CustomEvent) => void onEvent: (event: TrustedEvent) => void
} }
export type DVMRequest = { export type DVMRequest = {
@@ -120,7 +120,7 @@ export type DVMRequest = {
} }
export type DVMOpts = DVMRequest & { export type DVMOpts = DVMRequest & {
onEvent: (event: CustomEvent) => void onEvent: (event: TrustedEvent) => void
} }
export type FeedOptions = { export type FeedOptions = {
+8 -8
View File
@@ -1,12 +1,12 @@
import {inc, max, min, now} from '@welshman/lib' import {inc, max, min, now} from '@welshman/lib'
import type {CustomEvent, Filter} from '@welshman/util' import type {TrustedEvent, Filter} from '@welshman/util'
import {EPOCH, trimFilters, guessFilterDelta} from '@welshman/util' import {EPOCH, trimFilters, guessFilterDelta} from '@welshman/util'
import type {Feed, RequestItem, FeedOptions} from './core' import type {Feed, RequestItem, FeedOptions} from './core'
import {FeedType} from './core' import {FeedType} from './core'
import {FeedCompiler} from './compiler' import {FeedCompiler} from './compiler'
export type LoadOpts = { export type LoadOpts = {
onEvent?: (event: CustomEvent) => void onEvent?: (event: TrustedEvent) => void
onExhausted?: () => void onExhausted?: () => void
useWindowing?: boolean useWindowing?: boolean
} }
@@ -101,7 +101,7 @@ export class FeedLoader {
await this.options.request({ await this.options.request({
relays, relays,
filters: trimFilters(requestFilters), filters: trimFilters(requestFilters),
onEvent: (event: CustomEvent) => { onEvent: (event: TrustedEvent) => {
count += 1 count += 1
until = Math.min(until, event.created_at - 1) until = Math.min(until, event.created_at - 1)
onEvent?.(event) onEvent?.(event)
@@ -130,14 +130,14 @@ export class FeedLoader {
async _getDifferenceLoader(feeds: Feed[], {onEvent, onExhausted}: LoadOpts) { async _getDifferenceLoader(feeds: Feed[], {onEvent, onExhausted}: LoadOpts) {
const exhausted = new Set<number>() const exhausted = new Set<number>()
const skip = new Set<string>() const skip = new Set<string>()
const events: CustomEvent[] = [] const events: TrustedEvent[] = []
const seen = new Set() const seen = new Set()
const loaders = await Promise.all( const loaders = await Promise.all(
feeds.map((feed: Feed, i: number) => feeds.map((feed: Feed, i: number) =>
this.getLoader(feed, { this.getLoader(feed, {
onExhausted: () => exhausted.add(i), onExhausted: () => exhausted.add(i),
onEvent: (event: CustomEvent) => { onEvent: (event: TrustedEvent) => {
if (i === 0) { if (i === 0) {
events.push(event) events.push(event)
} else { } else {
@@ -175,14 +175,14 @@ export class FeedLoader {
async _getIntersectionLoader(feeds: Feed[], {onEvent, onExhausted}: LoadOpts) { async _getIntersectionLoader(feeds: Feed[], {onEvent, onExhausted}: LoadOpts) {
const exhausted = new Set<number>() const exhausted = new Set<number>()
const counts = new Map<string, number>() const counts = new Map<string, number>()
const events: CustomEvent[] = [] const events: TrustedEvent[] = []
const seen = new Set() const seen = new Set()
const loaders = await Promise.all( const loaders = await Promise.all(
feeds.map((feed: Feed, i: number) => feeds.map((feed: Feed, i: number) =>
this.getLoader(feed, { this.getLoader(feed, {
onExhausted: () => exhausted.add(i), onExhausted: () => exhausted.add(i),
onEvent: (event: CustomEvent) => { onEvent: (event: TrustedEvent) => {
events.push(event) events.push(event)
counts.set(event.id, inc(counts.get(event.id))) counts.set(event.id, inc(counts.get(event.id)))
}, },
@@ -222,7 +222,7 @@ export class FeedLoader {
feeds.map((feed: Feed, i: number) => feeds.map((feed: Feed, i: number) =>
this.getLoader(feed, { this.getLoader(feed, {
onExhausted: () => exhausted.add(i), onExhausted: () => exhausted.add(i),
onEvent: (event: CustomEvent) => { onEvent: (event: TrustedEvent) => {
if (!seen.has(event.id)) { if (!seen.has(event.id)) {
onEvent?.(event) onEvent?.(event)
seen.add(event.id) seen.add(event.id)
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@welshman/lib", "name": "@welshman/lib",
"version": "0.0.14", "version": "0.0.15",
"author": "hodlbod", "author": "hodlbod",
"license": "MIT", "license": "MIT",
"description": "A collection of utilities.", "description": "A collection of utilities.",
+5 -5
View File
@@ -1,4 +1,4 @@
import {UnwrappedEvent, SignedEvent, HashedEvent, EventTemplate, WRAP, SEAL} from '@welshman/util' import {UnwrappedEvent, SignedEvent, HashedEvent, StampedEvent, WRAP, SEAL} from '@welshman/util'
import {own, hash, decrypt, ISigner} from './util' import {own, hash, decrypt, ISigner} from './util'
import {Nip01Signer} from './signers/nip01' import {Nip01Signer} from './signers/nip01'
@@ -7,8 +7,8 @@ export const seen = new Map<string, UnwrappedEvent | Error>()
export const now = (drift = 0) => export const now = (drift = 0) =>
Math.round(Date.now() / 1000 - Math.random() * Math.pow(10, drift)) Math.round(Date.now() / 1000 - Math.random() * Math.pow(10, drift))
export const getRumor = async (signer: ISigner, template: EventTemplate) => export const getRumor = async (signer: ISigner, template: StampedEvent) =>
hash(own(await signer.getPubkey(), template)) hash(own(template, await signer.getPubkey()))
export const getSeal = async (signer: ISigner, pubkey: string, rumor: HashedEvent) => export const getSeal = async (signer: ISigner, pubkey: string, rumor: HashedEvent) =>
signer.sign(hash({ signer.sign(hash({
@@ -28,7 +28,7 @@ export const getWrap = async (wrapper: ISigner, pubkey: string, seal: SignedEven
tags: [...tags, ["p", pubkey]], tags: [...tags, ["p", pubkey]],
})) }))
export const wrap = async (signer: ISigner, wrapper: ISigner, pubkey: string, template: EventTemplate, tags: string[][] = []) => { export const wrap = async (signer: ISigner, wrapper: ISigner, pubkey: string, template: StampedEvent, tags: string[][] = []) => {
const rumor = await getRumor(signer, template) const rumor = await getRumor(signer, template)
const seal = await getSeal(signer, pubkey, rumor) const seal = await getSeal(signer, pubkey, rumor)
const wrap = await getWrap(wrapper, pubkey, seal, tags) const wrap = await getWrap(wrapper, pubkey, seal, tags)
@@ -77,7 +77,7 @@ export class Nip59 {
withWrapper = (wrapper: ISigner) => new Nip59(this.signer, wrapper) withWrapper = (wrapper: ISigner) => new Nip59(this.signer, wrapper)
wrap = (pubkey: string, template: EventTemplate, tags: string[][] = []) => wrap = (pubkey: string, template: StampedEvent, tags: string[][] = []) =>
wrap(this.signer, this.wrapper || Nip01Signer.ephemeral(), pubkey, template, tags) wrap(this.signer, this.wrapper || Nip01Signer.ephemeral(), pubkey, template, tags)
unwrap = (event: SignedEvent) => unwrap = (event: SignedEvent) =>
+2 -2
View File
@@ -1,4 +1,4 @@
import {EventTemplate} from '@welshman/util' import {StampedEvent} from '@welshman/util'
import {nip04, nip44, own, hash, sign, getPubkey, ISigner, makeSecret} from "../util" import {nip04, nip44, own, hash, sign, getPubkey, ISigner, makeSecret} from "../util"
export class Nip01Signer implements ISigner { export class Nip01Signer implements ISigner {
@@ -14,7 +14,7 @@ export class Nip01Signer implements ISigner {
getPubkey = async () => this.pubkey getPubkey = async () => this.pubkey
sign = async (event: EventTemplate) => sign(hash(own(this.pubkey, event)), this.secret) sign = async (event: StampedEvent) => sign(hash(own(event, this.pubkey)), this.secret)
nip04 = { nip04 = {
encrypt: async (pubkey: string, message: string) => encrypt: async (pubkey: string, message: string) =>
+3 -3
View File
@@ -1,4 +1,4 @@
import {EventTemplate} from '@welshman/util' import {StampedEvent} from '@welshman/util'
import {hash, own, Sign, ISigner, EncryptionImplementation} from '../util' import {hash, own, Sign, ISigner, EncryptionImplementation} from '../util'
export type Nip07 = { export type Nip07 = {
@@ -30,8 +30,8 @@ export class Nip07Signer implements ISigner {
getPubkey = async () => getNip07()!.getPublicKey()! getPubkey = async () => getNip07()!.getPublicKey()!
sign = async (template: EventTemplate) => { sign = async (template: StampedEvent) => {
const event = hash(own(await this.getPubkey(), template)) const event = hash(own(template, await this.getPubkey()))
return this.#then(ext => ext.signEvent(event)) return this.#then(ext => ext.signEvent(event))
} }
+4 -4
View File
@@ -1,7 +1,7 @@
import {finalizeEvent, getPublicKey} from "nostr-tools" import {finalizeEvent, getPublicKey} from "nostr-tools"
import {hexToBytes} from '@noble/hashes/utils' import {hexToBytes} from '@noble/hashes/utils'
import {Emitter, tryCatch, randomId, sleep, equals, now} from "@welshman/lib" import {Emitter, tryCatch, randomId, sleep, equals, now} from "@welshman/lib"
import {createEvent, TrustedEvent, EventTemplate, NOSTR_CONNECT} from "@welshman/util" import {createEvent, TrustedEvent, StampedEvent, NOSTR_CONNECT} from "@welshman/util"
import {subscribe, publish, Subscription} from "@welshman/net" import {subscribe, publish, Subscription} from "@welshman/net"
import {nip04, nip44, ISigner, decrypt, hash, own} from '../util' import {nip04, nip44, ISigner, decrypt, hash, own} from '../util'
import {Nip01Signer} from './nip01' import {Nip01Signer} from './nip01'
@@ -138,7 +138,7 @@ export class Nip46Broker extends Emitter {
return this.#connectResult === "ack" return this.#connectResult === "ack"
} }
signEvent = async (event: EventTemplate) => { signEvent = async (event: StampedEvent) => {
return JSON.parse(await this.request("sign_event", [JSON.stringify(event)]) as string) return JSON.parse(await this.request("sign_event", [JSON.stringify(event)]) as string)
} }
@@ -169,8 +169,8 @@ export class Nip46Signer implements ISigner {
getPubkey = async () => this.broker.pubkey getPubkey = async () => this.broker.pubkey
sign = (template: EventTemplate) => sign = (template: StampedEvent) =>
this.broker.signEvent(hash(own(this.broker.pubkey, template))) this.broker.signEvent(hash(own(template, this.broker.pubkey)))
nip04 = { nip04 = {
encrypt: this.broker.nip04Encrypt, encrypt: this.broker.nip04Encrypt,
+7 -5
View File
@@ -1,8 +1,8 @@
import {schnorr} from '@noble/curves/secp256k1' import {schnorr} from '@noble/curves/secp256k1'
import {bytesToHex, hexToBytes} from '@noble/hashes/utils' import {bytesToHex, hexToBytes} from '@noble/hashes/utils'
import {nip04 as nt04, nip44 as nt44, generateSecretKey, getPublicKey, getEventHash} from "nostr-tools" import {nip04 as nt04, nip44 as nt44, generateSecretKey, getPublicKey, getEventHash} from "nostr-tools"
import {cached} from '@welshman/lib' import {cached, now} from '@welshman/lib'
import {SignedEvent, HashedEvent, EventTemplate, OwnedEvent} from '@welshman/util' import {SignedEvent, HashedEvent, EventTemplate, StampedEvent, OwnedEvent} from '@welshman/util'
export const makeSecret = () => bytesToHex(generateSecretKey()) export const makeSecret = () => bytesToHex(generateSecretKey())
@@ -13,9 +13,11 @@ export const getHash = (event: OwnedEvent) => getEventHash(event)
export const getSig = (event: HashedEvent, secret: string) => export const getSig = (event: HashedEvent, secret: string) =>
bytesToHex(schnorr.sign(event.id, secret)) bytesToHex(schnorr.sign(event.id, secret))
export const own = (pubkey: string, event: EventTemplate) => ({...event, pubkey}) export const stamp = (event: EventTemplate, created_at = now()) => ({...event, created_at})
export const hash = (event: OwnedEvent): HashedEvent => ({...event, id: getHash(event)}) export const own = (event: StampedEvent, pubkey: string) => ({...event, pubkey})
export const hash = (event: OwnedEvent) => ({...event, id: getHash(event)})
export const sign = (event: HashedEvent, secret: string) => ({...event, sig: getSig(event, secret)}) export const sign = (event: HashedEvent, secret: string) => ({...event, sig: getSig(event, secret)})
@@ -35,7 +37,7 @@ export const nip44 = {
decrypt: (pubkey: string, secret: string, m: string) => nt44.v2.decrypt(m, nip44.getSharedSecret(secret, pubkey)), decrypt: (pubkey: string, secret: string, m: string) => nt44.v2.decrypt(m, nip44.getSharedSecret(secret, pubkey)),
} }
export type Sign = (event: EventTemplate) => Promise<SignedEvent> export type Sign = (event: StampedEvent) => Promise<SignedEvent>
export type Encrypt = (pubkey: string, message: string) => Promise<string> export type Encrypt = (pubkey: string, message: string) => Promise<string>
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@welshman/store", "name": "@welshman/store",
"version": "0.0.2", "version": "0.0.3",
"author": "hodlbod", "author": "hodlbod",
"license": "MIT", "license": "MIT",
"description": "A collection of utilities based on svelte/store for use with welshman", "description": "A collection of utilities based on svelte/store for use with welshman",
+12 -12
View File
@@ -5,7 +5,7 @@ import {identity, batch, partition, first} from "@welshman/lib"
import type {Maybe} from "@welshman/lib" import type {Maybe} from "@welshman/lib"
import type {Repository} from "@welshman/util" import type {Repository} from "@welshman/util"
import {matchFilters, getIdAndAddress, getIdFilters} from "@welshman/util" import {matchFilters, getIdAndAddress, getIdFilters} from "@welshman/util"
import type {Filter, CustomEvent} from "@welshman/util" import type {Filter, TrustedEvent} from "@welshman/util"
export const getter = <T>(store: Readable<T>) => { export const getter = <T>(store: Readable<T>) => {
let value: T let value: T
@@ -70,8 +70,8 @@ export function withGetter<T>(store: Readable<T> | Writable<T>) {
export const throttled = <T>(delay: number, store: Readable<T>) => export const throttled = <T>(delay: number, store: Readable<T>) =>
custom(set => store.subscribe(throttle(delay, set))) custom(set => store.subscribe(throttle(delay, set)))
export const createEventStore = (repository: Repository): Writable<CustomEvent[]> => { export const createEventStore = (repository: Repository): Writable<TrustedEvent[]> => {
let subs: Subscriber<CustomEvent[]>[] = [] let subs: Subscriber<TrustedEvent[]>[] = []
const onUpdate = throttle(300, () => { const onUpdate = throttle(300, () => {
const $events = repository.dump() const $events = repository.dump()
@@ -82,9 +82,9 @@ export const createEventStore = (repository: Repository): Writable<CustomEvent[]
}) })
return { return {
set: (events: CustomEvent[]) => repository.load(events), set: (events: TrustedEvent[]) => repository.load(events),
update: (f: Updater<CustomEvent[]>) => repository.load(f(repository.dump())), update: (f: Updater<TrustedEvent[]>) => repository.load(f(repository.dump())),
subscribe: (f: Subscriber<CustomEvent[]>) => { subscribe: (f: Subscriber<TrustedEvent[]>) => {
f(repository.dump()) f(repository.dump())
subs.push(f) subs.push(f)
@@ -112,8 +112,8 @@ export const deriveEventsMapped = <T>(repository: Repository, {
includeDeleted = false, includeDeleted = false,
}: { }: {
filters: Filter[] filters: Filter[]
eventToItem: (event: CustomEvent) => Maybe<T | Promise<T>> eventToItem: (event: TrustedEvent) => Maybe<T | Promise<T>>
itemToEvent: (item: T) => CustomEvent itemToEvent: (item: T) => TrustedEvent
throttle?: number throttle?: number
includeDeleted?: boolean includeDeleted?: boolean
}) => }) =>
@@ -121,7 +121,7 @@ export const deriveEventsMapped = <T>(repository: Repository, {
let data: T[] = [] let data: T[] = []
const deferred = new Set() const deferred = new Set()
const defer = (event: CustomEvent, item: Promise<T>) => { const defer = (event: TrustedEvent, item: Promise<T>) => {
deferred.add(event.id) deferred.add(event.id)
item.then($item => { item.then($item => {
@@ -149,7 +149,7 @@ export const deriveEventsMapped = <T>(repository: Repository, {
setter(data) setter(data)
const onUpdate = batch(300, (updates: {added: CustomEvent[]; removed: Set<string>}[]) => { const onUpdate = batch(300, (updates: {added: TrustedEvent[]; removed: Set<string>}[]) => {
const removed = new Set() const removed = new Set()
const added = new Map() const added = new Map()
@@ -203,7 +203,7 @@ export const deriveEventsMapped = <T>(repository: Repository, {
}, {throttle}) }, {throttle})
export const deriveEvents = (repository: Repository, opts: {filters: Filter[], includeDeleted?: boolean}) => export const deriveEvents = (repository: Repository, opts: {filters: Filter[], includeDeleted?: boolean}) =>
deriveEventsMapped<CustomEvent>(repository, { deriveEventsMapped<TrustedEvent>(repository, {
...opts, ...opts,
eventToItem: identity, eventToItem: identity,
itemToEvent: identity, itemToEvent: identity,
@@ -218,7 +218,7 @@ export const deriveEvent = (repository: Repository, idOrAddress: string) =>
first first
) )
export const deriveIsDeletedByAddress = (repository: Repository, event: CustomEvent) => export const deriveIsDeletedByAddress = (repository: Repository, event: TrustedEvent) =>
custom<boolean>(setter => { custom<boolean>(setter => {
setter(repository.isDeletedByAddress(event)) setter(repository.isDeletedByAddress(event))
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@welshman/util", "name": "@welshman/util",
"version": "0.0.25", "version": "0.0.26",
"author": "hodlbod", "author": "hodlbod",
"license": "MIT", "license": "MIT",
"description": "A collection of nostr-related utilities.", "description": "A collection of nostr-related utilities.",
+3 -3
View File
@@ -1,4 +1,4 @@
import type {EventContent, CustomEvent} from './Events' import type {EventContent, TrustedEvent} from './Events'
export type Encrypt = (x: string) => Promise<string> export type Encrypt = (x: string) => Promise<string>
@@ -14,11 +14,11 @@ export type EncryptableResult = {
content: string content: string
} }
export type DecryptedEvent = CustomEvent & { export type DecryptedEvent = TrustedEvent & {
plaintext: Partial<EventContent> plaintext: Partial<EventContent>
} }
export const asDecryptedEvent = (event: CustomEvent, plaintext: Partial<EventContent>) => export const asDecryptedEvent = (event: TrustedEvent, plaintext: Partial<EventContent>) =>
({...event, plaintext}) as DecryptedEvent ({...event, plaintext}) as DecryptedEvent
export class Encryptable { export class Encryptable {
+13 -7
View File
@@ -12,10 +12,13 @@ export type EventContent = {
export type EventTemplate = EventContent & { export type EventTemplate = EventContent & {
kind: number kind: number
}
export type StampedEvent = EventTemplate & {
created_at: number created_at: number
} }
export type OwnedEvent = EventTemplate & { export type OwnedEvent = StampedEvent & {
pubkey: string pubkey: string
} }
@@ -38,9 +41,6 @@ export type TrustedEvent = HashedEvent & {
[verifiedSymbol]?: boolean [verifiedSymbol]?: boolean
} }
/* eslint @typescript-eslint/no-empty-interface: 0 */
export interface CustomEvent extends TrustedEvent {}
export type CreateEventOpts = { export type CreateEventOpts = {
content?: string content?: string
tags?: string[][] tags?: string[][]
@@ -51,10 +51,13 @@ export const createEvent = (kind: number, {content = "", tags = [], created_at =
({kind, content, tags, created_at}) ({kind, content, tags, created_at})
export const isEventTemplate = (e: EventTemplate): e is EventTemplate => export const isEventTemplate = (e: EventTemplate): e is EventTemplate =>
Boolean(typeof e.kind === "number" && e.tags && typeof e.content === "string" && e.created_at) Boolean(typeof e.kind === "number" && e.tags && typeof e.content === "string")
export const isStampedEvent = (e: StampedEvent): e is StampedEvent =>
Boolean(isEventTemplate(e) && e.created_at)
export const isOwnedEvent = (e: OwnedEvent): e is OwnedEvent => export const isOwnedEvent = (e: OwnedEvent): e is OwnedEvent =>
Boolean(isEventTemplate(e) && e.pubkey) Boolean(isStampedEvent(e) && e.pubkey)
export const isHashedEvent = (e: HashedEvent): e is HashedEvent => export const isHashedEvent = (e: HashedEvent): e is HashedEvent =>
Boolean(isOwnedEvent(e) && e.id) Boolean(isOwnedEvent(e) && e.id)
@@ -69,6 +72,9 @@ export const isTrustedEvent = (e: TrustedEvent): e is TrustedEvent =>
isSignedEvent(e) || isUnwrappedEvent(e) isSignedEvent(e) || isUnwrappedEvent(e)
export const asEventTemplate = (e: EventTemplate): EventTemplate => export const asEventTemplate = (e: EventTemplate): EventTemplate =>
pick(['kind', 'tags', 'content'], e)
export const asStampedEvent = (e: StampedEvent): StampedEvent =>
pick(['kind', 'tags', 'content', 'created_at'], e) pick(['kind', 'tags', 'content', 'created_at'], e)
export const asOwnedEvent = (e: OwnedEvent): OwnedEvent => export const asOwnedEvent = (e: OwnedEvent): OwnedEvent =>
@@ -118,7 +124,7 @@ export const isPlainReplaceable = (e: EventTemplate) => isPlainReplaceableKind(e
export const isParameterizedReplaceable = (e: EventTemplate) => isParameterizedReplaceableKind(e.kind) export const isParameterizedReplaceable = (e: EventTemplate) => isParameterizedReplaceableKind(e.kind)
export const isChildOf = (child: EventTemplate, parent: HashedEvent) => { export const isChildOf = (child: EventContent, parent: HashedEvent) => {
const {roots, replies} = Tags.fromEvent(child).ancestors() const {roots, replies} = Tags.fromEvent(child).ancestors()
const parentIds = (replies.exists() ? replies : roots).values().valueOf() const parentIds = (replies.exists() ? replies : roots).values().valueOf()
+2 -2
View File
@@ -1,6 +1,6 @@
import {matchFilter as nostrToolsMatchFilter} from 'nostr-tools' import {matchFilter as nostrToolsMatchFilter} from 'nostr-tools'
import {uniqBy, prop, mapVals, shuffle, avg, hash, groupBy, randomId, uniq} from '@welshman/lib' import {uniqBy, prop, mapVals, shuffle, avg, hash, groupBy, randomId, uniq} from '@welshman/lib'
import type {HashedEvent, CustomEvent, SignedEvent} from './Events' import type {HashedEvent, TrustedEvent, SignedEvent} from './Events'
import {isReplaceableKind} from './Kinds' import {isReplaceableKind} from './Kinds'
import {Address, getAddress} from './Address' import {Address, getAddress} from './Address'
@@ -155,7 +155,7 @@ export const getIdFilters = (idsOrAddresses: string[]) => {
return filters return filters
} }
export const getReplyFilters = (events: CustomEvent[], filter: Filter) => { export const getReplyFilters = (events: TrustedEvent[], filter: Filter) => {
const a = [] const a = []
const e = [] const e = []
+4 -4
View File
@@ -1,7 +1,7 @@
import {fromPairs, last, first, parseJson} from "@welshman/lib" import {fromPairs, last, first, parseJson} from "@welshman/lib"
import {getAddress} from "./Address" import {getAddress} from "./Address"
import {getAddressTags, getKindTagValues} from "./Tags" import {getAddressTags, getKindTagValues} from "./Tags"
import type {CustomEvent} from "./Events" import type {TrustedEvent} from "./Events"
export type Handler = { export type Handler = {
kind: number kind: number
@@ -9,13 +9,13 @@ export type Handler = {
about: string about: string
image: string image: string
identifier: string identifier: string
event: CustomEvent event: TrustedEvent
website?: string website?: string
lud16?: string lud16?: string
nip05?: string nip05?: string
} }
export const readHandlers = (event: CustomEvent) => { export const readHandlers = (event: TrustedEvent) => {
const {d: identifier} = fromPairs(event.tags) const {d: identifier} = fromPairs(event.tags)
const meta = parseJson(event.content) const meta = parseJson(event.content)
const normalizedMeta = { const normalizedMeta = {
@@ -40,7 +40,7 @@ export const getHandlerKey = (handler: Handler) => `${handler.kind}:${getAddress
export const displayHandler = (handler?: Handler, fallback = "") => handler?.name || fallback export const displayHandler = (handler?: Handler, fallback = "") => handler?.name || fallback
export const getHandlerAddress = (event: CustomEvent) => { export const getHandlerAddress = (event: TrustedEvent) => {
const tags = getAddressTags(event.tags) const tags = getAddressTags(event.tags)
const tag = tags.find(t => last(t) === "web") || first(tags) const tag = tags.find(t => last(t) === "web") || first(tags)
+4 -4
View File
@@ -1,6 +1,6 @@
import {nip19} from "nostr-tools" import {nip19} from "nostr-tools"
import {ellipsize, parseJson} from "@welshman/lib" import {ellipsize, parseJson} from "@welshman/lib"
import {CustomEvent} from "./Events" import {TrustedEvent} from "./Events"
import {PROFILE} from "./Kinds" import {PROFILE} from "./Kinds"
export type Profile = { export type Profile = {
@@ -13,11 +13,11 @@ export type Profile = {
picture?: string picture?: string
website?: string website?: string
display_name?: string display_name?: string
event?: CustomEvent event?: TrustedEvent
} }
export type PublishedProfile = Omit<Profile, "event"> & { export type PublishedProfile = Omit<Profile, "event"> & {
event: CustomEvent event: TrustedEvent
} }
export const isPublishedProfile = (profile: Profile): profile is PublishedProfile => export const isPublishedProfile = (profile: Profile): profile is PublishedProfile =>
@@ -36,7 +36,7 @@ export const makeProfile = (profile: Partial<Profile> = {}): Profile => ({
...profile, ...profile,
}) })
export const readProfile = (event: CustomEvent) => { export const readProfile = (event: TrustedEvent) => {
const profile = parseJson(event.content) || {} const profile = parseJson(event.content) || {}
return {...profile, event} as PublishedProfile return {...profile, event} as PublishedProfile
+3 -3
View File
@@ -2,7 +2,7 @@ import {last, Emitter, normalizeUrl, sleep, stripProtocol} from '@welshman/lib'
import {matchFilters} from './Filters' import {matchFilters} from './Filters'
import type {Repository} from './Repository' import type {Repository} from './Repository'
import type {Filter} from './Filters' import type {Filter} from './Filters'
import type {CustomEvent} from './Events' import type {TrustedEvent} from './Events'
// Constants and types // Constants and types
@@ -84,13 +84,13 @@ export class Relay extends Emitter {
send(type: string, ...message: any[]) { send(type: string, ...message: any[]) {
switch(type) { switch(type) {
case 'EVENT': return this.handleEVENT(message as [CustomEvent]) case 'EVENT': return this.handleEVENT(message as [TrustedEvent])
case 'CLOSE': return this.handleCLOSE(message as [string]) case 'CLOSE': return this.handleCLOSE(message as [string])
case 'REQ': return this.handleREQ(message as [string, ...Filter[]]) case 'REQ': return this.handleREQ(message as [string, ...Filter[]])
} }
} }
handleEVENT([event]: [CustomEvent]) { handleEVENT([event]: [TrustedEvent]) {
this.repository.publish(event) this.repository.publish(event)
// Callers generally expect async relays // Callers generally expect async relays
+20 -20
View File
@@ -4,19 +4,19 @@ import {EPOCH, matchFilter} from './Filters'
import {isReplaceable, isTrustedEvent} from './Events' import {isReplaceable, isTrustedEvent} from './Events'
import {getAddress} from './Address' import {getAddress} from './Address'
import type {Filter} from './Filters' import type {Filter} from './Filters'
import type {CustomEvent} from './Events' import type {TrustedEvent} from './Events'
export const DAY = 86400 export const DAY = 86400
const getDay = (ts: number) => Math.floor(ts / DAY) const getDay = (ts: number) => Math.floor(ts / DAY)
export class Repository extends Emitter { export class Repository extends Emitter {
eventsById = new Map<string, CustomEvent>() eventsById = new Map<string, TrustedEvent>()
eventsByWrap = new Map<string, CustomEvent>() eventsByWrap = new Map<string, TrustedEvent>()
eventsByAddress = new Map<string, CustomEvent>() eventsByAddress = new Map<string, TrustedEvent>()
eventsByTag = new Map<string, CustomEvent[]>() eventsByTag = new Map<string, TrustedEvent[]>()
eventsByDay = new Map<number, CustomEvent[]>() eventsByDay = new Map<number, TrustedEvent[]>()
eventsByAuthor = new Map<string, CustomEvent[]>() eventsByAuthor = new Map<string, TrustedEvent[]>()
deletes = new Map<string, number>() deletes = new Map<string, number>()
// Dump/load/clear // Dump/load/clear
@@ -25,7 +25,7 @@ export class Repository extends Emitter {
return Array.from(this.eventsById.values()) return Array.from(this.eventsById.values())
} }
load = async (events: CustomEvent[], chunkSize = 1000) => { load = async (events: TrustedEvent[], chunkSize = 1000) => {
this.clear() this.clear()
const added = [] const added = []
@@ -69,7 +69,7 @@ export class Repository extends Emitter {
: this.eventsById.get(idOrAddress) : this.eventsById.get(idOrAddress)
} }
hasEvent = (event: CustomEvent) => { hasEvent = (event: TrustedEvent) => {
const duplicate = ( const duplicate = (
this.eventsById.get(event.id) || this.eventsById.get(event.id) ||
this.eventsByAddress.get(getAddress(event)) this.eventsByAddress.get(getAddress(event))
@@ -79,12 +79,12 @@ export class Repository extends Emitter {
} }
query = (filters: Filter[], {includeDeleted = false} = {}) => { query = (filters: Filter[], {includeDeleted = false} = {}) => {
const result: CustomEvent[][] = [] const result: TrustedEvent[][] = []
for (let filter of filters) { for (let filter of filters) {
let events: CustomEvent[] = Array.from(this.eventsById.values()) let events: TrustedEvent[] = Array.from(this.eventsById.values())
if (filter.ids) { if (filter.ids) {
events = filter.ids!.map(id => this.eventsById.get(id)).filter(identity) as CustomEvent[] events = filter.ids!.map(id => this.eventsById.get(id)).filter(identity) as TrustedEvent[]
filter = omit(['ids'], filter) filter = omit(['ids'], filter)
} else if (filter.authors) { } else if (filter.authors) {
events = uniq(filter.authors!.flatMap(pubkey => this.eventsByAuthor.get(pubkey) || [])) events = uniq(filter.authors!.flatMap(pubkey => this.eventsByAuthor.get(pubkey) || []))
@@ -112,8 +112,8 @@ export class Repository extends Emitter {
} }
} }
const chunk: CustomEvent[] = [] const chunk: TrustedEvent[] = []
for (const event of sortBy((e: CustomEvent) => -e.created_at, events)) { for (const event of sortBy((e: TrustedEvent) => -e.created_at, events)) {
if (filter.limit && chunk.length >= filter.limit) { if (filter.limit && chunk.length >= filter.limit) {
break break
} }
@@ -133,7 +133,7 @@ export class Repository extends Emitter {
return uniq(flatten(result)) return uniq(flatten(result))
} }
publish = (event: CustomEvent, {shouldNotify = true} = {}): boolean => { publish = (event: TrustedEvent, {shouldNotify = true} = {}): boolean => {
if (!isTrustedEvent(event)) { if (!isTrustedEvent(event)) {
throw new Error("Invalid event published to Repository", event) throw new Error("Invalid event published to Repository", event)
} }
@@ -203,19 +203,19 @@ export class Repository extends Emitter {
return true return true
} }
isDeletedByAddress = (event: CustomEvent) => (this.deletes.get(getAddress(event)) || 0) > event.created_at isDeletedByAddress = (event: TrustedEvent) => (this.deletes.get(getAddress(event)) || 0) > event.created_at
isDeletedById = (event: CustomEvent) => (this.deletes.get(event.id) || 0) > event.created_at isDeletedById = (event: TrustedEvent) => (this.deletes.get(event.id) || 0) > event.created_at
isDeleted = (event: CustomEvent) => this.isDeletedByAddress(event) || this.isDeletedById(event) isDeleted = (event: TrustedEvent) => this.isDeletedByAddress(event) || this.isDeletedById(event)
// Utilities // Utilities
_updateIndex<K>(m: Map<K, CustomEvent[]>, k: K, e: CustomEvent, duplicate?: CustomEvent) { _updateIndex<K>(m: Map<K, TrustedEvent[]>, k: K, e: TrustedEvent, duplicate?: TrustedEvent) {
let a = m.get(k) || [] let a = m.get(k) || []
if (duplicate) { if (duplicate) {
a = a.filter((x: CustomEvent) => x !== duplicate) a = a.filter((x: TrustedEvent) => x !== duplicate)
} }
a.push(e) a.push(e)
+8 -8
View File
@@ -1,6 +1,6 @@
import {first, splitAt, identity, sortBy, uniq, shuffle, pushToMapKey} from '@welshman/lib' import {first, splitAt, identity, sortBy, uniq, shuffle, pushToMapKey} from '@welshman/lib'
import {Tags} from './Tags' import {Tags} from './Tags'
import type {CustomEvent} from './Events' import type {TrustedEvent} from './Events'
import {isShareableRelayUrl} from './Relay' import {isShareableRelayUrl} from './Relay'
import {isCommunityAddress, isGroupAddress} from './Address' import {isCommunityAddress, isGroupAddress} from './Address'
@@ -172,19 +172,19 @@ export class Router {
this.getPubkeySelection(pubkey, RelayMode.Inbox), this.getPubkeySelection(pubkey, RelayMode.Inbox),
]).policy(this.addMinimalFallbacks) ]).policy(this.addMinimalFallbacks)
Event = (event: CustomEvent) => Event = (event: TrustedEvent) =>
this.scenario(this.forceValue(event.id, [ this.scenario(this.forceValue(event.id, [
this.getPubkeySelection(event.pubkey, RelayMode.Write), this.getPubkeySelection(event.pubkey, RelayMode.Write),
...this.getContextSelections(Tags.fromEvent(event).context()), ...this.getContextSelections(Tags.fromEvent(event).context()),
])) ]))
EventChildren = (event: CustomEvent) => EventChildren = (event: TrustedEvent) =>
this.scenario(this.forceValue(event.id, [ this.scenario(this.forceValue(event.id, [
this.getPubkeySelection(event.pubkey, RelayMode.Read), this.getPubkeySelection(event.pubkey, RelayMode.Read),
...this.getContextSelections(Tags.fromEvent(event).context()), ...this.getContextSelections(Tags.fromEvent(event).context()),
])) ]))
EventAncestors = (event: CustomEvent, type: "mentions" | "replies" | "roots") => { EventAncestors = (event: TrustedEvent, type: "mentions" | "replies" | "roots") => {
const tags = Tags.fromEvent(event) const tags = Tags.fromEvent(event)
const ancestors = tags.ancestors()[type] const ancestors = tags.ancestors()[type]
const pubkeys = tags.values("p").valueOf() const pubkeys = tags.values("p").valueOf()
@@ -201,13 +201,13 @@ export class Router {
return this.product(ancestors.values().valueOf(), relays) return this.product(ancestors.values().valueOf(), relays)
} }
EventMentions = (event: CustomEvent) => this.EventAncestors(event, "mentions") EventMentions = (event: TrustedEvent) => this.EventAncestors(event, "mentions")
EventParents = (event: CustomEvent) => this.EventAncestors(event, "replies") EventParents = (event: TrustedEvent) => this.EventAncestors(event, "replies")
EventRoots = (event: CustomEvent) => this.EventAncestors(event, "roots") EventRoots = (event: TrustedEvent) => this.EventAncestors(event, "roots")
PublishEvent = (event: CustomEvent) => { PublishEvent = (event: TrustedEvent) => {
const tags = Tags.fromEvent(event) const tags = Tags.fromEvent(event)
const mentions = tags.values("p").valueOf() const mentions = tags.values("p").valueOf()
+2 -3
View File
@@ -1,4 +1,3 @@
import {EventTemplate} from 'nostr-tools'
import type {OmitStatics} from '@welshman/lib' import type {OmitStatics} from '@welshman/lib'
import {Fluent, nth, nthEq, ensurePlural} from '@welshman/lib' import {Fluent, nth, nthEq, ensurePlural} from '@welshman/lib'
import {isRelayUrl, normalizeRelayUrl} from './Relay' import {isRelayUrl, normalizeRelayUrl} from './Relay'
@@ -42,9 +41,9 @@ export class Tags extends (Fluent<Tag> as OmitStatics<typeof Fluent<Tag>, 'from'
static wrap = (p: Iterable<string[]>) => new Tags(Array.from(p).map(Tag.from)) static wrap = (p: Iterable<string[]>) => new Tags(Array.from(p).map(Tag.from))
static fromEvent = (event: Pick<EventTemplate, "tags">) => Tags.wrap(event.tags || []) static fromEvent = (event: {tags: string[][]}) => Tags.wrap(event.tags || [])
static fromEvents = (events: Pick<EventTemplate, "tags">[]) => Tags.wrap(events.flatMap(e => e.tags || [])) static fromEvents = (events: {tags: string[][]}[]) => Tags.wrap(events.flatMap(e => e.tags || []))
static fromIMeta = (imeta: string[]) => Tags.wrap(imeta.map((m: string) => m.split(" "))) static fromIMeta = (imeta: string[]) => Tags.wrap(imeta.map((m: string) => m.split(" ")))
+4 -4
View File
@@ -1,5 +1,5 @@
import {hexToBech32} from '@welshman/lib' import {hexToBech32} from '@welshman/lib'
import type {CustomEvent} from './Events' import type {TrustedEvent} from './Events'
import {Tags} from "./Tags" import {Tags} from "./Tags"
const DIVISORS = { const DIVISORS = {
@@ -81,12 +81,12 @@ export type Zapper = {
} }
export type Zap = { export type Zap = {
request: CustomEvent request: TrustedEvent
response: CustomEvent, response: TrustedEvent,
invoiceAmount: number invoiceAmount: number
} }
export const zapFromEvent = (response: CustomEvent, zapper: Zapper) => { export const zapFromEvent = (response: TrustedEvent, zapper: Zapper) => {
const responseMeta = Tags.fromEvent(response).asObject() const responseMeta = Tags.fromEvent(response).asObject()
let zap: Zap let zap: Zap