applesauce-common 5.0.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # applesauce-common
2
2
 
3
- AppleSauce is a collection of utilities for building reactive nostr applications. The common package provides NIP-specific helpers, models, operations, and utilities for working with various Nostr Improvement Proposals (NIPs). This package contains all the extra functionality that applications can use with nostr events that is not directly related to the core protocol.
3
+ Applesauce is a collection of utilities for building reactive nostr applications. The common package provides NIP-specific helpers, models, operations, and utilities for working with various Nostr Improvement Proposals (NIPs). This package contains all the extra functionality that applications can use with nostr events that is not directly related to the core protocol.
4
4
 
5
5
  ## Installation
6
6
 
@@ -33,8 +33,8 @@ pnpm add applesauce-common
33
33
 
34
34
  For detailed documentation and guides, visit:
35
35
 
36
- - [Getting Started](https://hzrd149.github.io/applesauce/introduction/getting-started)
37
- - [API Reference](https://hzrd149.github.io/applesauce/typedoc/)
36
+ - [Getting Started](https://applesauce.build/introduction/getting-started)
37
+ - [API Reference](https://applesauce.build/typedoc/)
38
38
 
39
39
  ## Example
40
40
 
@@ -21,4 +21,5 @@ export * from "./share.js";
21
21
  export * from "./stream.js";
22
22
  export * from "./torrent.js";
23
23
  export * from "./wrapped-message.js";
24
+ export * from "./zap-goal.js";
24
25
  import "../register.js";
@@ -21,5 +21,6 @@ export * from "./share.js";
21
21
  export * from "./stream.js";
22
22
  export * from "./torrent.js";
23
23
  export * from "./wrapped-message.js";
24
+ export * from "./zap-goal.js";
24
25
  // Register the common blueprints with the event factory
25
26
  import "../register.js";
@@ -0,0 +1,16 @@
1
+ import { EventBlueprint } from "applesauce-core/event-factory";
2
+ import { MetaTagOptions } from "applesauce-core/operations";
3
+ import { ZapOptions } from "../operations/zap-split.js";
4
+ export type ZapGoalBlueprintOptions = MetaTagOptions & ZapOptions & {
5
+ /** Unix timestamp when the goal closes */
6
+ closedAt?: number;
7
+ /** Image URL for the goal */
8
+ image?: string;
9
+ /** Brief summary of the goal */
10
+ summary?: string;
11
+ };
12
+ /**
13
+ * NIP-75 Zap Goal event (kind 9041) blueprint
14
+ * Creates a zap goal event with description, target amount, and relays
15
+ */
16
+ export declare function ZapGoalBlueprint(description: string, amount: number, relays: string[], opts?: ZapGoalBlueprintOptions): EventBlueprint;
@@ -0,0 +1,12 @@
1
+ import { blueprint } from "applesauce-core/event-factory";
2
+ import { setContent, setMetaTags } from "applesauce-core/operations";
3
+ import { ZAP_GOAL_KIND } from "../helpers/zap-goal.js";
4
+ import * as ZapGoal from "../operations/zap-goal.js";
5
+ import { setZapSplit } from "../operations/zap-split.js";
6
+ /**
7
+ * NIP-75 Zap Goal event (kind 9041) blueprint
8
+ * Creates a zap goal event with description, target amount, and relays
9
+ */
10
+ export function ZapGoalBlueprint(description, amount, relays, opts) {
11
+ return blueprint(ZAP_GOAL_KIND, setContent(description), ZapGoal.setAmount(amount), ZapGoal.setRelays(relays), opts?.closedAt ? ZapGoal.setClosedAt(opts.closedAt) : undefined, opts?.image ? ZapGoal.setImage(opts.image) : undefined, opts?.summary ? ZapGoal.setSummary(opts.summary) : undefined, setZapSplit(opts), setMetaTags({ ...opts, alt: opts?.alt ?? `Zap Goal: ${opts?.summary || description}` }));
12
+ }
@@ -0,0 +1,14 @@
1
+ import { NostrEvent } from "applesauce-core/helpers/event";
2
+ import { type CodeSnippetEvent } from "../helpers/code-snippet.js";
3
+ import { CastRefEventStore, EventCast } from "./cast.js";
4
+ export declare class CodeSnippet extends EventCast<CodeSnippetEvent> {
5
+ constructor(event: NostrEvent, store: CastRefEventStore);
6
+ get language(): string;
7
+ get name(): string;
8
+ get description(): string | undefined;
9
+ get extension(): string;
10
+ get runtime(): string | undefined;
11
+ get license(): string[];
12
+ get repo(): string | undefined;
13
+ get dependencies(): string[];
14
+ }
@@ -0,0 +1,33 @@
1
+ import { getCodeSnippetDependencies, getCodeSnippetDescription, getCodeSnippetExtension, getCodeSnippetLanguage, getCodeSnippetLicense, getCodeSnippetName, getCodeSnippetRepo, getCodeSnippetRuntime, isValidCodeSnippet, } from "../helpers/code-snippet.js";
2
+ import { EventCast } from "./cast.js";
3
+ export class CodeSnippet extends EventCast {
4
+ constructor(event, store) {
5
+ if (!isValidCodeSnippet(event))
6
+ throw new Error("Invalid code snippet");
7
+ super(event, store);
8
+ }
9
+ get language() {
10
+ return getCodeSnippetLanguage(this.event);
11
+ }
12
+ get name() {
13
+ return getCodeSnippetName(this.event);
14
+ }
15
+ get description() {
16
+ return getCodeSnippetDescription(this.event);
17
+ }
18
+ get extension() {
19
+ return getCodeSnippetExtension(this.event) || "ts";
20
+ }
21
+ get runtime() {
22
+ return getCodeSnippetRuntime(this.event);
23
+ }
24
+ get license() {
25
+ return getCodeSnippetLicense(this.event);
26
+ }
27
+ get repo() {
28
+ return getCodeSnippetRepo(this.event);
29
+ }
30
+ get dependencies() {
31
+ return getCodeSnippetDependencies(this.event);
32
+ }
33
+ }
@@ -1,6 +1,7 @@
1
1
  export * from "./article.js";
2
2
  export * from "./bookmarks.js";
3
3
  export * from "./cast.js";
4
+ export * from "./code-snippet.js";
4
5
  export * from "./comment.js";
5
6
  export * from "./groups.js";
6
7
  export * from "./mutes.js";
@@ -16,3 +17,4 @@ export * from "./stream.js";
16
17
  export * from "./torrent.js";
17
18
  export * from "./user.js";
18
19
  export * from "./zap.js";
20
+ export * from "./zap-goal.js";
@@ -1,6 +1,7 @@
1
1
  export * from "./article.js";
2
2
  export * from "./bookmarks.js";
3
3
  export * from "./cast.js";
4
+ export * from "./code-snippet.js";
4
5
  export * from "./comment.js";
5
6
  export * from "./groups.js";
6
7
  export * from "./mutes.js";
@@ -16,3 +17,4 @@ export * from "./stream.js";
16
17
  export * from "./torrent.js";
17
18
  export * from "./user.js";
18
19
  export * from "./zap.js";
20
+ export * from "./zap-goal.js";
@@ -33,6 +33,8 @@ export declare class User {
33
33
  get searchRelays$(): ChainableObservable<import("./relay-lists.js").SearchRelays | undefined>;
34
34
  get blockedRelays$(): ChainableObservable<import("./relay-lists.js").BlockedRelays | undefined>;
35
35
  get directMessageRelays$(): ChainableObservable<string[] | undefined>;
36
+ /** Get the users kind 10063 Blossom servers list */
37
+ get blossomServers$(): ChainableObservable<URL[] | undefined>;
36
38
  /** Gets the users list of NIP-29 groups */
37
39
  get groups$(): ChainableObservable<import("./groups.js").GroupsList | undefined>;
38
40
  /** Get the latest live stream for the user */
@@ -1,5 +1,6 @@
1
1
  import { isEvent, isHexKey, kinds, nprofileEncode, npubEncode, } from "applesauce-core/helpers";
2
- import { combineLatest, defer, from, map, switchMap, tap } from "rxjs";
2
+ import { combineLatest, defer, from, map, ReplaySubject, share, switchMap, tap, } from "rxjs";
3
+ import { BLOSSOM_SERVER_LIST_KIND, getBlossomServersFromList } from "../helpers/blossom.js";
3
4
  import { GROUPS_LIST_KIND } from "../helpers/groups.js";
4
5
  import { getRelaysFromList } from "../helpers/lists.js";
5
6
  import { FAVORITE_RELAYS_KIND } from "../helpers/relay-list.js";
@@ -21,7 +22,21 @@ export function castUser(user, store) {
21
22
  return newUser;
22
23
  }
23
24
  }
25
+ function memoize() {
26
+ return share({
27
+ connector: () => new ReplaySubject(1),
28
+ resetOnRefCountZero: false,
29
+ resetOnComplete: false,
30
+ });
31
+ }
24
32
  // IMPORTANT: this class MUST use async import() to import the other classes so that we do not get circular dependency errors
33
+ const Circular = {
34
+ Profile: defer(() => from(import("./profile.js"))).pipe(memoize()),
35
+ Mutes: defer(() => from(import("./mutes.js"))).pipe(memoize()),
36
+ Bookmarks: defer(() => from(import("./bookmarks.js"))).pipe(memoize()),
37
+ RelayLists: defer(() => from(import("./relay-lists.js"))).pipe(memoize()),
38
+ Groups: defer(() => from(import("./groups.js"))).pipe(memoize()),
39
+ };
25
40
  /** A class for a user */
26
41
  export class User {
27
42
  pubkey;
@@ -71,7 +86,7 @@ export class User {
71
86
  }
72
87
  // Observable interfaces
73
88
  get profile$() {
74
- return this.$$ref("profile$", (store) => defer(() => from(import("./profile.js").then((m) => m.Profile))).pipe(switchMap((Profile) => store.replaceable({ kind: kinds.Metadata, pubkey: this.pubkey }).pipe(castEventStream(Profile, store)))));
89
+ return this.$$ref("profile$", (store) => Circular.Profile.pipe(switchMap(({ Profile }) => store.replaceable({ kind: kinds.Metadata, pubkey: this.pubkey }).pipe(castEventStream(Profile, store)))));
75
90
  }
76
91
  get contacts$() {
77
92
  return this.$$ref("contacts$", (store) => this.outboxes$.pipe(
@@ -81,14 +96,9 @@ export class User {
81
96
  map((arr) => arr.map((p) => castUser(p, this.#store)))));
82
97
  }
83
98
  get mutes$() {
84
- return this.$$ref("mutes$", (store) => combineLatest([
85
- // Import the Mutes class
86
- defer(() => import("./mutes.js").then((m) => m.Mutes)),
87
- // Always start without the outboxes
88
- this.outboxes$,
89
- ]).pipe(
99
+ return this.$$ref("mutes$", (store) => combineLatest([Circular.Mutes, this.outboxes$]).pipe(
90
100
  // Create the mute list event with the outboxes
91
- switchMap(([Mutes, outboxes]) => store
101
+ switchMap(([{ Mutes }, outboxes]) => store
92
102
  .event({ kind: kinds.Mutelist, pubkey: this.pubkey, relays: outboxes })
93
103
  .pipe(castEventStream(Mutes, store)))));
94
104
  }
@@ -104,52 +114,32 @@ export class User {
104
114
  return this.mailboxes$.inboxes;
105
115
  }
106
116
  get bookmarks$() {
107
- return this.$$ref("bookmarks$", (store) => combineLatest([
108
- // Import the BookmarksList class
109
- defer(() => from(import("./bookmarks.js").then((m) => m.BookmarksList))),
110
- // Get outboxes and start without them
111
- this.outboxes$,
112
- ]).pipe(switchMap(([BookmarksList, outboxes]) =>
117
+ return this.$$ref("bookmarks$", (store) => combineLatest([Circular.Bookmarks, this.outboxes$]).pipe(switchMap(([{ BookmarksList }, outboxes]) =>
113
118
  // Fetch the bookmarks list event from the outboxes
114
119
  store
115
120
  .replaceable({ kind: kinds.BookmarkList, pubkey: this.pubkey, relays: outboxes })
116
121
  .pipe(castEventStream(BookmarksList, store)))));
117
122
  }
118
123
  get favoriteRelays$() {
119
- return this.$$ref("favoriteRelays$", (store) => combineLatest([
120
- // Import the FavoriteRelays class
121
- defer(() => from(import("./relay-lists.js").then((m) => m.FavoriteRelays))),
122
- // Get outboxes and start without them
123
- this.outboxes$,
124
- ]).pipe(
124
+ return this.$$ref("favoriteRelays$", (store) => combineLatest([Circular.RelayLists, this.outboxes$]).pipe(
125
125
  // Fetch the favorite relays list event from the outboxes
126
- switchMap(([FavoriteRelaysList, outboxes]) => store
126
+ switchMap(([{ FavoriteRelays }, outboxes]) => store
127
127
  .replaceable({ kind: FAVORITE_RELAYS_KIND, pubkey: this.pubkey, relays: outboxes })
128
- .pipe(castEventStream(FavoriteRelaysList, store)))));
128
+ .pipe(castEventStream(FavoriteRelays, store)))));
129
129
  }
130
130
  get searchRelays$() {
131
- return this.$$ref("searchRelays$", (store) => combineLatest([
132
- // Import the SearchRelays class
133
- defer(() => from(import("./relay-lists.js").then((m) => m.SearchRelays))),
134
- // Get outboxes and start without them
135
- this.outboxes$,
136
- ]).pipe(
131
+ return this.$$ref("searchRelays$", (store) => combineLatest([Circular.RelayLists, this.outboxes$]).pipe(
137
132
  // Fetch the search relays list event from the outboxes
138
- switchMap(([SearchRelaysList, outboxes]) => store
133
+ switchMap(([{ SearchRelays }, outboxes]) => store
139
134
  .replaceable({ kind: kinds.SearchRelaysList, pubkey: this.pubkey, relays: outboxes })
140
- .pipe(castEventStream(SearchRelaysList, store)))));
135
+ .pipe(castEventStream(SearchRelays, store)))));
141
136
  }
142
137
  get blockedRelays$() {
143
- return this.$$ref("blockedRelays$", (store) => combineLatest([
144
- // Import the BlockedRelays class
145
- defer(() => from(import("./relay-lists.js").then((m) => m.BlockedRelays))),
146
- // Get outboxes and start without them
147
- this.outboxes$,
148
- ]).pipe(
138
+ return this.$$ref("blockedRelays$", (store) => combineLatest([Circular.RelayLists, this.outboxes$]).pipe(
149
139
  // Fetch the blocked relays list event from the outboxes
150
- switchMap(([BlockedRelaysList, outboxes]) => store
140
+ switchMap(([{ BlockedRelays }, outboxes]) => store
151
141
  .replaceable({ kind: kinds.BlockedRelaysList, pubkey: this.pubkey, relays: outboxes })
152
- .pipe(castEventStream(BlockedRelaysList, store)))));
142
+ .pipe(castEventStream(BlockedRelays, store)))));
153
143
  }
154
144
  get directMessageRelays$() {
155
145
  return this.$$ref("dmRelays$", (store) => this.outboxes$.pipe(
@@ -158,14 +148,17 @@ export class User {
158
148
  .replaceable({ kind: kinds.DirectMessageRelaysList, pubkey: this.pubkey, relays: outboxes })
159
149
  .pipe(map((event) => event && getRelaysFromList(event))))));
160
150
  }
151
+ /** Get the users kind 10063 Blossom servers list */
152
+ get blossomServers$() {
153
+ return this.$$ref("blossomServers$", (store) => this.outboxes$.pipe(
154
+ // Fetch the blossom servers list event from the outboxes
155
+ switchMap((outboxes) => store
156
+ .replaceable({ kind: BLOSSOM_SERVER_LIST_KIND, pubkey: this.pubkey, relays: outboxes })
157
+ .pipe(map((event) => event && getBlossomServersFromList(event))))));
158
+ }
161
159
  /** Gets the users list of NIP-29 groups */
162
160
  get groups$() {
163
- return this.$$ref("groups$", (store) => combineLatest([
164
- // Import the BlockedRelays class
165
- defer(() => from(import("./groups.js").then((m) => m.GroupsList))),
166
- // Get outboxes and start without them
167
- this.outboxes$,
168
- ]).pipe(switchMap(([GroupsList, outboxes]) => store
161
+ return this.$$ref("groups$", (store) => combineLatest([Circular.Groups, this.outboxes$]).pipe(switchMap(([{ GroupsList }, outboxes]) => store
169
162
  .replaceable({ kind: GROUPS_LIST_KIND, pubkey: this.pubkey, relays: outboxes })
170
163
  .pipe(castEventStream(GroupsList, store)))));
171
164
  }
@@ -0,0 +1,18 @@
1
+ import { NostrEvent } from "applesauce-core/helpers";
2
+ import { ZapGoalEvent, ZapGoalProgress } from "../helpers/zap-goal.js";
3
+ import { CastRefEventStore, EventCast } from "./cast.js";
4
+ /** Cast a kind 9041 event to a ZapGoal */
5
+ export declare class ZapGoal extends EventCast<ZapGoalEvent> {
6
+ constructor(event: NostrEvent, store: CastRefEventStore);
7
+ get amount(): number | undefined;
8
+ get relays(): string[];
9
+ get closedAt(): number | undefined;
10
+ get image(): string | undefined;
11
+ get summary(): string | undefined;
12
+ get beneficiaries(): import("../helpers/zap.js").ZapSplit[] | undefined;
13
+ get description(): string;
14
+ /** An observable of all zaps contributing to this goal */
15
+ get zaps$(): import("../observable/chainable.js").ChainableObservable<import("applesauce-core/helpers").KnownEvent<9735>[]>;
16
+ /** An observable of the goal progress */
17
+ get progress$(): import("../observable/chainable.js").ChainableObservable<ZapGoalProgress | undefined>;
18
+ }
@@ -0,0 +1,47 @@
1
+ import { combineLatest, map, of } from "rxjs";
2
+ import { getZapGoalAmount, getZapGoalBeneficiaries, getZapGoalClosedAt, getZapGoalImage, getZapGoalProgress, getZapGoalRelays, getZapGoalSummary, isValidZapGoal, } from "../helpers/zap-goal.js";
3
+ import { EventZapsModel } from "../models/zaps.js";
4
+ import { EventCast } from "./cast.js";
5
+ /** Cast a kind 9041 event to a ZapGoal */
6
+ export class ZapGoal extends EventCast {
7
+ constructor(event, store) {
8
+ if (!isValidZapGoal(event))
9
+ throw new Error("Invalid zap goal");
10
+ super(event, store);
11
+ }
12
+ get amount() {
13
+ return getZapGoalAmount(this.event);
14
+ }
15
+ get relays() {
16
+ return getZapGoalRelays(this.event);
17
+ }
18
+ get closedAt() {
19
+ return getZapGoalClosedAt(this.event);
20
+ }
21
+ get image() {
22
+ return getZapGoalImage(this.event);
23
+ }
24
+ get summary() {
25
+ return getZapGoalSummary(this.event);
26
+ }
27
+ get beneficiaries() {
28
+ return getZapGoalBeneficiaries(this.event);
29
+ }
30
+ get description() {
31
+ return this.event.content;
32
+ }
33
+ /** An observable of all zaps contributing to this goal */
34
+ get zaps$() {
35
+ return this.$$ref("zaps$", (store) => {
36
+ return store.model(EventZapsModel, this.event);
37
+ });
38
+ }
39
+ /** An observable of the goal progress */
40
+ get progress$() {
41
+ return this.$$ref("progress$", (_store) => {
42
+ return combineLatest([of(this.event), this.zaps$]).pipe(map(([goal, zaps]) => {
43
+ return getZapGoalProgress(goal, zaps);
44
+ }));
45
+ });
46
+ }
47
+ }
@@ -0,0 +1,25 @@
1
+ import { KnownEvent, NostrEvent } from "applesauce-core/helpers/event";
2
+ export declare const CODE_SNIPPET_KIND = 1337;
3
+ /** Type for validated code snippet events */
4
+ export type CodeSnippetEvent = KnownEvent<typeof CODE_SNIPPET_KIND>;
5
+ /** Returns the language tag value */
6
+ export declare function getCodeSnippetLanguage(snippet: CodeSnippetEvent): string;
7
+ export declare function getCodeSnippetLanguage(snippet: NostrEvent): string | undefined;
8
+ /** Returns the name tag value */
9
+ export declare function getCodeSnippetName(snippet: CodeSnippetEvent): string;
10
+ export declare function getCodeSnippetName(snippet: NostrEvent): string | undefined;
11
+ /** Returns the description tag value */
12
+ export declare function getCodeSnippetDescription(snippet: NostrEvent): string | undefined;
13
+ /** Returns the extension tag value */
14
+ export declare function getCodeSnippetExtension(snippet: CodeSnippetEvent): string;
15
+ export declare function getCodeSnippetExtension(snippet: NostrEvent): string | undefined;
16
+ /** Returns the runtime tag value */
17
+ export declare function getCodeSnippetRuntime(snippet: NostrEvent): string | undefined;
18
+ /** Returns all license tag values (can be repeated per NIP-C0 for multi-licensing) */
19
+ export declare function getCodeSnippetLicense(snippet: NostrEvent): string[];
20
+ /** Returns the repository tag value (URL or NIP-34 Git repository reference) */
21
+ export declare function getCodeSnippetRepo(snippet: NostrEvent): string | undefined;
22
+ /** Returns all "dep" tag values */
23
+ export declare function getCodeSnippetDependencies(snippet: NostrEvent): string[];
24
+ /** Validates that an event is a valid code snippet event */
25
+ export declare function isValidCodeSnippet(snippet: NostrEvent): snippet is CodeSnippetEvent;
@@ -0,0 +1,37 @@
1
+ import { getTagValue } from "applesauce-core/helpers/event";
2
+ import { processTags } from "applesauce-core/helpers/tags";
3
+ // Code snippet kind (NIP-C0)
4
+ export const CODE_SNIPPET_KIND = 1337;
5
+ export function getCodeSnippetLanguage(snippet) {
6
+ return getTagValue(snippet, "l");
7
+ }
8
+ export function getCodeSnippetName(snippet) {
9
+ return getTagValue(snippet, "name");
10
+ }
11
+ /** Returns the description tag value */
12
+ export function getCodeSnippetDescription(snippet) {
13
+ return getTagValue(snippet, "description");
14
+ }
15
+ export function getCodeSnippetExtension(snippet) {
16
+ return getTagValue(snippet, "extension");
17
+ }
18
+ /** Returns the runtime tag value */
19
+ export function getCodeSnippetRuntime(snippet) {
20
+ return getTagValue(snippet, "runtime");
21
+ }
22
+ /** Returns all license tag values (can be repeated per NIP-C0 for multi-licensing) */
23
+ export function getCodeSnippetLicense(snippet) {
24
+ return processTags(snippet.tags, (t) => (t[0] === "license" ? t : undefined), (t) => (t[1] ? t[1] : undefined));
25
+ }
26
+ /** Returns the repository tag value (URL or NIP-34 Git repository reference) */
27
+ export function getCodeSnippetRepo(snippet) {
28
+ return getTagValue(snippet, "repo");
29
+ }
30
+ /** Returns all "dep" tag values */
31
+ export function getCodeSnippetDependencies(snippet) {
32
+ return processTags(snippet.tags, (t) => (t[0] === "dep" ? t : undefined), (t) => (t[1] ? t[1] : undefined));
33
+ }
34
+ /** Validates that an event is a valid code snippet event */
35
+ export function isValidCodeSnippet(snippet) {
36
+ return snippet.kind === CODE_SNIPPET_KIND && snippet.content.length > 0;
37
+ }
@@ -1,14 +1,17 @@
1
1
  import { NostrEvent } from "applesauce-core/helpers/event";
2
+ import { AddressPointer } from "applesauce-core/helpers/pointers";
2
3
  export type Emoji = {
3
4
  /** The emoji shortcode (without the ::) */
4
5
  shortcode: string;
5
6
  /** The URL to the emoji image */
6
7
  url: string;
8
+ /** The NIP-01 "a" tag address of the emoji pack this emoji belongs to */
9
+ address?: AddressPointer;
7
10
  };
8
11
  /** Gets an "emoji" tag that matches an emoji code */
9
12
  export declare function getEmojiTag(tags: {
10
13
  tags: string[][];
11
- } | string[][], code: string): ["emoji", string, string] | undefined;
14
+ } | string[][], code: string): ["emoji", string, string, ...string[]] | undefined;
12
15
  /** Gets an emoji for a shortcode from an array of tags or event */
13
16
  export declare function getEmojiFromTags(event: {
14
17
  tags: string[][];
@@ -1,4 +1,5 @@
1
1
  import { getTagValue } from "applesauce-core/helpers/event";
2
+ import { parseReplaceableAddress } from "applesauce-core/helpers/pointers";
2
3
  /** Gets an "emoji" tag that matches an emoji code */
3
4
  export function getEmojiTag(tags, code) {
4
5
  code = code.replace(/^:|:$/g, "").toLowerCase();
@@ -9,10 +10,8 @@ export function getEmojiFromTags(event, code) {
9
10
  const tag = getEmojiTag(event, code);
10
11
  if (!tag)
11
12
  return undefined;
12
- return {
13
- shortcode: tag[1],
14
- url: tag[2],
15
- };
13
+ const address = tag[3] ? parseReplaceableAddress(tag[3]) : undefined;
14
+ return address ? { shortcode: tag[1], url: tag[2], address } : { shortcode: tag[1], url: tag[2] };
16
15
  }
17
16
  /** Returns the name of a NIP-30 emoji pack */
18
17
  export function getPackName(pack) {
@@ -22,7 +21,12 @@ export function getPackName(pack) {
22
21
  export function getEmojis(pack) {
23
22
  return pack.tags
24
23
  .filter((t) => t[0] === "emoji" && t[1] && t[2])
25
- .map((t) => ({ shortcode: t[1], url: t[2] }));
24
+ .map((t) => {
25
+ const address = t[3] ? parseReplaceableAddress(t[3]) : undefined;
26
+ return address
27
+ ? { shortcode: t[1], url: t[2], address }
28
+ : { shortcode: t[1], url: t[2] };
29
+ });
26
30
  }
27
31
  /** Returns the custom emoji for a reaction event */
28
32
  export function getReactionEmoji(event) {
@@ -34,4 +34,5 @@ export * from "./torrent.js";
34
34
  export * from "./user-status.js";
35
35
  export * from "./wrapped-messages.js";
36
36
  export * from "./zap.js";
37
+ export * from "./zap-goal.js";
37
38
  export * from "./relay-list.js";
@@ -34,4 +34,5 @@ export * from "./torrent.js";
34
34
  export * from "./user-status.js";
35
35
  export * from "./wrapped-messages.js";
36
36
  export * from "./zap.js";
37
+ export * from "./zap-goal.js";
37
38
  export * from "./relay-list.js";
@@ -0,0 +1,63 @@
1
+ import { KnownEvent, NostrEvent } from "applesauce-core/helpers/event";
2
+ import { ZapSplit } from "./zap.js";
3
+ export declare const ZAP_GOAL_KIND = 9041;
4
+ export declare const ZapGoalAmountSymbol: unique symbol;
5
+ export declare const ZapGoalRelaysSymbol: unique symbol;
6
+ export declare const ZapGoalProgressSymbol: unique symbol;
7
+ export type ZapGoalEvent = KnownEvent<typeof ZAP_GOAL_KIND>;
8
+ export interface ZapGoalProgress {
9
+ total: number;
10
+ target: number;
11
+ percentage: number;
12
+ remaining: number;
13
+ }
14
+ /**
15
+ * Get the target amount in milisats from a zap goal event
16
+ * Returns undefined if the amount tag is missing or invalid
17
+ */
18
+ export declare function getZapGoalAmount(event: NostrEvent): number | undefined;
19
+ /**
20
+ * Get the relay URLs from a zap goal event
21
+ * Returns empty array if no relays tag is found
22
+ */
23
+ export declare function getZapGoalRelays(event: NostrEvent): string[];
24
+ /**
25
+ * Get the closed_at timestamp from a zap goal event
26
+ * Returns undefined if no closed_at tag is found
27
+ */
28
+ export declare function getZapGoalClosedAt(event: NostrEvent): number | undefined;
29
+ /**
30
+ * Get the image URL from a zap goal event
31
+ * Returns undefined if no image tag is found
32
+ */
33
+ export declare function getZapGoalImage(event: NostrEvent): string | undefined;
34
+ /**
35
+ * Get the summary from a zap goal event
36
+ * Returns undefined if no summary tag is found
37
+ */
38
+ export declare function getZapGoalSummary(event: NostrEvent): string | undefined;
39
+ /**
40
+ * Get the beneficiaries from a zap goal event
41
+ * Returns undefined if no zap tags are found
42
+ * Uses the existing getZapSplits helper
43
+ */
44
+ export declare function getZapGoalBeneficiaries(event: NostrEvent): ZapSplit[] | undefined;
45
+ /**
46
+ * Get the goal tag from an event (for linking events to goals)
47
+ * Returns undefined if no goal tag is found
48
+ */
49
+ export declare function getGoalTag(event: NostrEvent): {
50
+ goalId: string;
51
+ relay?: string;
52
+ } | undefined;
53
+ /**
54
+ * Checks if a zap goal event is valid (has required tags)
55
+ * Acts as a type guard that casts to ZapGoalEvent
56
+ */
57
+ export declare function isValidZapGoal(event?: NostrEvent): event is ZapGoalEvent;
58
+ /**
59
+ * Calculates progress for a zap goal from zap events
60
+ * Filters zaps by the goal's relay list and closed_at timestamp
61
+ * Returns undefined if target amount is invalid
62
+ */
63
+ export declare function getZapGoalProgress(goal: NostrEvent, zaps: NostrEvent[]): ZapGoalProgress | undefined;
@@ -0,0 +1,127 @@
1
+ import { relaySet } from "applesauce-core/helpers";
2
+ import { getOrComputeCachedValue } from "applesauce-core/helpers/cache";
3
+ import { getTagValue } from "applesauce-core/helpers/event";
4
+ import { getZapAmount, getZapSplits, isValidZap } from "./zap.js";
5
+ // NIP-75 Zap Goal kind
6
+ export const ZAP_GOAL_KIND = 9041;
7
+ // Cache symbols
8
+ export const ZapGoalAmountSymbol = Symbol.for("zap-goal-amount");
9
+ export const ZapGoalRelaysSymbol = Symbol.for("zap-goal-relays");
10
+ export const ZapGoalProgressSymbol = Symbol.for("zap-goal-progress");
11
+ /**
12
+ * Get the target amount in milisats from a zap goal event
13
+ * Returns undefined if the amount tag is missing or invalid
14
+ */
15
+ export function getZapGoalAmount(event) {
16
+ return getOrComputeCachedValue(event, ZapGoalAmountSymbol, () => {
17
+ const amount = getTagValue(event, "amount");
18
+ if (!amount)
19
+ return undefined;
20
+ const parsed = parseInt(amount, 10);
21
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
22
+ });
23
+ }
24
+ /**
25
+ * Get the relay URLs from a zap goal event
26
+ * Returns empty array if no relays tag is found
27
+ */
28
+ export function getZapGoalRelays(event) {
29
+ return getOrComputeCachedValue(event, ZapGoalRelaysSymbol, () => {
30
+ return relaySet(event.tags.find((tag) => tag[0] === "relays")?.slice(1));
31
+ });
32
+ }
33
+ /**
34
+ * Get the closed_at timestamp from a zap goal event
35
+ * Returns undefined if no closed_at tag is found
36
+ */
37
+ export function getZapGoalClosedAt(event) {
38
+ const closedAt = getTagValue(event, "closed_at");
39
+ return closedAt ? parseInt(closedAt, 10) : undefined;
40
+ }
41
+ /**
42
+ * Get the image URL from a zap goal event
43
+ * Returns undefined if no image tag is found
44
+ */
45
+ export function getZapGoalImage(event) {
46
+ return getTagValue(event, "image");
47
+ }
48
+ /**
49
+ * Get the summary from a zap goal event
50
+ * Returns undefined if no summary tag is found
51
+ */
52
+ export function getZapGoalSummary(event) {
53
+ return getTagValue(event, "summary");
54
+ }
55
+ /**
56
+ * Get the beneficiaries from a zap goal event
57
+ * Returns undefined if no zap tags are found
58
+ * Uses the existing getZapSplits helper
59
+ */
60
+ export function getZapGoalBeneficiaries(event) {
61
+ return getZapSplits(event);
62
+ }
63
+ /**
64
+ * Get the goal tag from an event (for linking events to goals)
65
+ * Returns undefined if no goal tag is found
66
+ */
67
+ export function getGoalTag(event) {
68
+ const goalTag = event.tags.find((tag) => tag[0] === "goal" && tag[1]);
69
+ if (!goalTag)
70
+ return undefined;
71
+ return {
72
+ goalId: goalTag[1],
73
+ relay: goalTag[2],
74
+ };
75
+ }
76
+ /**
77
+ * Checks if a zap goal event is valid (has required tags)
78
+ * Acts as a type guard that casts to ZapGoalEvent
79
+ */
80
+ export function isValidZapGoal(event) {
81
+ if (!event)
82
+ return false;
83
+ if (event.kind !== ZAP_GOAL_KIND)
84
+ return false;
85
+ // Required tags
86
+ if (getZapGoalAmount(event) === undefined)
87
+ return false;
88
+ if (getZapGoalRelays(event).length === 0)
89
+ return false;
90
+ return true;
91
+ }
92
+ /**
93
+ * Calculates progress for a zap goal from zap events
94
+ * Filters zaps by the goal's relay list and closed_at timestamp
95
+ * Returns undefined if target amount is invalid
96
+ */
97
+ export function getZapGoalProgress(goal, zaps) {
98
+ const target = getZapGoalAmount(goal);
99
+ if (target === undefined)
100
+ return undefined;
101
+ const closedAt = getZapGoalClosedAt(goal);
102
+ // Filter zaps that are valid and match the goal's criteria
103
+ const validZaps = zaps.filter((zap) => {
104
+ if (!isValidZap(zap))
105
+ return false;
106
+ // Check if zap was published before closed_at (if set)
107
+ if (closedAt !== undefined && zap.created_at >= closedAt)
108
+ return false;
109
+ // Check if zap request has relays that match goal relays
110
+ // This is a simplified check - in practice, you'd want to check the zap request's relays tag
111
+ // For now, we'll accept all valid zaps and let the relay filtering happen at the relay level
112
+ return true;
113
+ });
114
+ // Sum all zap amounts
115
+ const total = validZaps.reduce((sum, zap) => {
116
+ const amount = getZapAmount(zap);
117
+ return sum + (amount ?? 0);
118
+ }, 0);
119
+ const percentage = target > 0 ? (total / target) * 100 : 0;
120
+ const remaining = Math.max(0, target - total);
121
+ return {
122
+ total,
123
+ target,
124
+ percentage,
125
+ remaining,
126
+ };
127
+ }
@@ -15,5 +15,6 @@ export * from "./gift-wrap.js";
15
15
  export * from "./relay-lists.js";
16
16
  export * from "./stream.js";
17
17
  export * from "./shares.js";
18
+ export * from "./zap-goals.js";
18
19
  export * from "applesauce-core/models";
19
20
  import "../register.js";
@@ -15,6 +15,7 @@ export * from "./gift-wrap.js";
15
15
  export * from "./relay-lists.js";
16
16
  export * from "./stream.js";
17
17
  export * from "./shares.js";
18
+ export * from "./zap-goals.js";
18
19
  // Export all models from core
19
20
  export * from "applesauce-core/models";
20
21
  // Register the common models with the event store
@@ -24,7 +24,7 @@ export type ThreadModelOptions = {
24
24
  /** A model that returns a NIP-10 thread of events */
25
25
  export declare function ThreadModel(root: string | AddressPointer | EventPointer, opts?: ThreadModelOptions): Model<Thread>;
26
26
  /** A model that gets all legacy and NIP-10, and NIP-22 replies for an event */
27
- export declare function RepliesModel(event: NostrEvent, overrideKinds?: number[]): Model<NostrEvent[]>;
27
+ export declare function RepliesModel(event: NostrEvent | EventPointer | AddressPointer, overrideKinds?: number[]): Model<NostrEvent[]>;
28
28
  declare module "applesauce-core/event-store" {
29
29
  interface EventModels {
30
30
  /** Subscribe to a thread */
@@ -1,7 +1,7 @@
1
1
  import { EventModels } from "applesauce-core/event-store";
2
2
  import { buildCommonEventRelationFilters } from "applesauce-core/helpers";
3
3
  import { getEventUID, kinds } from "applesauce-core/helpers/event";
4
- import { eventMatchesPointer, getReplaceableAddressFromPointer, isAddressPointer, } from "applesauce-core/helpers/pointers";
4
+ import { eventMatchesPointer, getReplaceableAddressFromPointer, isAddressPointer, isEventPointer, isAddressPointerSame, isEventPointerSame, } from "applesauce-core/helpers/pointers";
5
5
  import { map } from "rxjs/operators";
6
6
  import { COMMENT_KIND, getCommentReplyPointer } from "../helpers/comment.js";
7
7
  import { getNip10References } from "../helpers/threading.js";
@@ -74,20 +74,36 @@ export function RepliesModel(event, overrideKinds) {
74
74
  if (reply.kind === kinds.ShortTextNote) {
75
75
  // Check if a NIP-10 reply is a direct reply to this event
76
76
  const refs = getNip10References(reply);
77
- const pointer = refs.reply?.a || refs.reply?.e;
78
- if (!pointer)
77
+ // Ingore if event is not replying to anything
78
+ if (!refs.reply)
79
79
  return false;
80
- return eventMatchesPointer(event, pointer);
80
+ // If the input was provided as an event pointer, test the reply.e
81
+ if (isEventPointer(event))
82
+ return refs.reply?.e && isEventPointerSame(event, refs.reply.e);
83
+ // If the input was provided as an address pointer, test the reply.a
84
+ else if (isAddressPointer(event))
85
+ return refs.reply?.a && isAddressPointerSame(event, refs.reply.a);
86
+ // Else test the reply against the event
87
+ else
88
+ return eventMatchesPointer(event, refs.reply?.a || refs.reply?.e);
81
89
  }
82
90
  else if (reply.kind === COMMENT_KIND) {
83
91
  // Check if a NIP-22 reply is a direct reply to this event
84
92
  const pointer = getCommentReplyPointer(reply);
85
93
  if (!pointer)
86
94
  return false;
87
- if (pointer.type === "address")
95
+ // Ignore external pointers
96
+ if (pointer.type === "external")
97
+ return true;
98
+ // Input is an event pointer, check if they match
99
+ if (isEventPointer(event))
100
+ return pointer.type === "event" ? isEventPointerSame(event, pointer) : false;
101
+ // Input is an address pointer, check if they match
102
+ else if (isAddressPointer(event))
103
+ return pointer.type === "address" ? isAddressPointerSame(event, pointer) : false;
104
+ // Else test the reply against the event
105
+ else
88
106
  return eventMatchesPointer(event, pointer);
89
- else if (pointer.type === "event")
90
- return pointer.id === event.id;
91
107
  }
92
108
  return false;
93
109
  })));
@@ -0,0 +1,9 @@
1
+ import { Model } from "applesauce-core/event-store";
2
+ import { EventPointer, NostrEvent } from "applesauce-core/helpers";
3
+ import { ZapGoalEvent, ZapGoalProgress } from "../helpers/zap-goal.js";
4
+ /** A model that returns all zap goals created by a user */
5
+ export declare function UserGoalsModel(pubkey: string): Model<ZapGoalEvent[]>;
6
+ /** A model that returns all zaps for a specific goal */
7
+ export declare function GoalZapsModel(goal: NostrEvent | EventPointer | string): Model<NostrEvent[]>;
8
+ /** A model that returns calculated progress for a goal */
9
+ export declare function GoalProgressModel(goal: NostrEvent | EventPointer | string): Model<ZapGoalProgress | undefined>;
@@ -0,0 +1,28 @@
1
+ import { combineLatest, map } from "rxjs";
2
+ import { ZAP_GOAL_KIND, getZapGoalProgress, isValidZapGoal, } from "../helpers/zap-goal.js";
3
+ import { EventZapsModel } from "./zaps.js";
4
+ /** A model that returns all zap goals created by a user */
5
+ export function UserGoalsModel(pubkey) {
6
+ return (events) => events
7
+ .timeline([{ kinds: [ZAP_GOAL_KIND], authors: [pubkey] }])
8
+ .pipe(map((events) => events.filter(isValidZapGoal)));
9
+ }
10
+ /** A model that returns all zaps for a specific goal */
11
+ export function GoalZapsModel(goal) {
12
+ return (events) => {
13
+ const goalId = typeof goal === "string" ? goal : goal.id;
14
+ return events.model(EventZapsModel, goalId);
15
+ };
16
+ }
17
+ /** A model that returns calculated progress for a goal */
18
+ export function GoalProgressModel(goal) {
19
+ return (events) => {
20
+ const goalEvent$ = events.event(goal);
21
+ const zaps$ = events.model(GoalZapsModel, goal);
22
+ return combineLatest([goalEvent$, zaps$]).pipe(map(([goalEvent, zaps]) => {
23
+ if (!goalEvent)
24
+ return undefined;
25
+ return getZapGoalProgress(goalEvent, zaps);
26
+ }));
27
+ };
28
+ }
@@ -25,4 +25,5 @@ export * as StreamChat from "./stream-chat.js";
25
25
  export * as Torrent from "./torrent.js";
26
26
  export * as WrappedMessage from "./wrapped-message.js";
27
27
  export * as Zap from "./zap-split.js";
28
+ export * as ZapGoal from "./zap-goal.js";
28
29
  export * as TagOperations from "./tag/index.js";
@@ -25,4 +25,5 @@ export * as StreamChat from "./stream-chat.js";
25
25
  export * as Torrent from "./torrent.js";
26
26
  export * as WrappedMessage from "./wrapped-message.js";
27
27
  export * as Zap from "./zap-split.js";
28
+ export * as ZapGoal from "./zap-goal.js";
28
29
  export * as TagOperations from "./tag/index.js";
@@ -0,0 +1,18 @@
1
+ import { EventOperation } from "applesauce-core/event-factory";
2
+ /** Sets the target amount in milisats for a zap goal */
3
+ export declare function setAmount(amount: number): EventOperation;
4
+ /** Sets the relay URLs for a zap goal */
5
+ export declare function setRelays(relays: string[]): EventOperation;
6
+ /** Sets the closed_at timestamp for a zap goal */
7
+ export declare function setClosedAt(timestamp: number): EventOperation;
8
+ /** Sets the image URL for a zap goal */
9
+ export declare function setImage(url: string): EventOperation;
10
+ /** Sets the summary for a zap goal */
11
+ export declare function setSummary(summary: string): EventOperation;
12
+ /** Sets all beneficiaries for a zap goal using zap split tags */
13
+ export declare function setBeneficiaries(beneficiaries: Array<{
14
+ pubkey: string;
15
+ weight: number;
16
+ }>): EventOperation;
17
+ /** Sets a goal tag on an event (for linking events to goals) */
18
+ export declare function setGoalTag(goalId: string, relay?: string): EventOperation;
@@ -0,0 +1,38 @@
1
+ import { fillAndTrimTag } from "applesauce-core/helpers";
2
+ import { modifyPublicTags } from "applesauce-core/operations";
3
+ import { includeSingletonTag } from "applesauce-core/operations/tags";
4
+ import { setZapSplitTags } from "./zap-split.js";
5
+ /** Sets the target amount in milisats for a zap goal */
6
+ export function setAmount(amount) {
7
+ return includeSingletonTag(["amount", amount.toString()], true);
8
+ }
9
+ /** Sets the relay URLs for a zap goal */
10
+ export function setRelays(relays) {
11
+ return modifyPublicTags((tags) => {
12
+ // Remove existing relays tags
13
+ const filteredTags = tags.filter((tag) => tag[0] !== "relays");
14
+ // Add new relays tags
15
+ const relayTags = relays.map((url) => ["relays", url]);
16
+ return [...filteredTags, ...relayTags];
17
+ });
18
+ }
19
+ /** Sets the closed_at timestamp for a zap goal */
20
+ export function setClosedAt(timestamp) {
21
+ return includeSingletonTag(["closed_at", timestamp.toString()], true);
22
+ }
23
+ /** Sets the image URL for a zap goal */
24
+ export function setImage(url) {
25
+ return includeSingletonTag(["image", url], true);
26
+ }
27
+ /** Sets the summary for a zap goal */
28
+ export function setSummary(summary) {
29
+ return includeSingletonTag(["summary", summary], true);
30
+ }
31
+ /** Sets all beneficiaries for a zap goal using zap split tags */
32
+ export function setBeneficiaries(beneficiaries) {
33
+ return setZapSplitTags(beneficiaries);
34
+ }
35
+ /** Sets a goal tag on an event (for linking events to goals) */
36
+ export function setGoalTag(goalId, relay) {
37
+ return includeSingletonTag(fillAndTrimTag(["goal", goalId, relay]), true);
38
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "applesauce-common",
3
- "version": "5.0.0",
3
+ "version": "5.2.0",
4
4
  "description": "Common NIP-specific helpers and models for applesauce",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -83,7 +83,7 @@
83
83
  },
84
84
  "dependencies": {
85
85
  "@scure/base": "^1.2.4",
86
- "applesauce-core": "^5.0.0",
86
+ "applesauce-core": "^5.2.0",
87
87
  "hash-sum": "^2.0.0",
88
88
  "light-bolt11-decoder": "^3.2.0",
89
89
  "rxjs": "^7.8.1"
@@ -94,7 +94,7 @@
94
94
  "@types/debug": "^4.1.12",
95
95
  "@types/hash-sum": "^1.0.2",
96
96
  "@types/node": "^22.19.1",
97
- "ajv": "^8.17.1",
97
+ "ajv": "^8.18.0",
98
98
  "ajv-formats": "^3.0.1",
99
99
  "nostr-tools": "^2.19",
100
100
  "rimraf": "^6.0.1",