applesauce-core 0.11.0 → 0.12.1

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.
Files changed (41) hide show
  1. package/dist/event-store/__tests__/event-store.test.js +45 -1
  2. package/dist/event-store/database.d.ts +2 -1
  3. package/dist/event-store/database.js +6 -7
  4. package/dist/event-store/event-store.d.ts +15 -5
  5. package/dist/event-store/event-store.js +72 -24
  6. package/dist/event-store/index.d.ts +1 -0
  7. package/dist/event-store/index.js +1 -0
  8. package/dist/event-store/interface.d.ts +29 -0
  9. package/dist/helpers/__tests__/nip-19.test.d.ts +1 -0
  10. package/dist/helpers/__tests__/nip-19.test.js +42 -0
  11. package/dist/helpers/cache.d.ts +3 -4
  12. package/dist/helpers/cache.js +1 -1
  13. package/dist/helpers/direct-messages.d.ts +4 -0
  14. package/dist/helpers/direct-messages.js +5 -0
  15. package/dist/helpers/event.d.ts +10 -2
  16. package/dist/helpers/event.js +5 -0
  17. package/dist/helpers/gift-wraps.d.ts +12 -0
  18. package/dist/helpers/gift-wraps.js +49 -0
  19. package/dist/helpers/hidden-content.d.ts +48 -0
  20. package/dist/helpers/hidden-content.js +88 -0
  21. package/dist/helpers/hidden-tags.d.ts +10 -28
  22. package/dist/helpers/hidden-tags.js +24 -59
  23. package/dist/helpers/index.d.ts +3 -0
  24. package/dist/helpers/index.js +3 -0
  25. package/dist/helpers/mutes.d.ts +1 -0
  26. package/dist/helpers/mutes.js +2 -1
  27. package/dist/helpers/nip-19.d.ts +4 -0
  28. package/dist/helpers/nip-19.js +27 -0
  29. package/dist/observable/claim-latest.d.ts +3 -2
  30. package/dist/observable/claim-latest.js +2 -1
  31. package/dist/observable/with-immediate-value.d.ts +3 -0
  32. package/dist/observable/with-immediate-value.js +19 -0
  33. package/dist/queries/mutes.js +1 -1
  34. package/dist/queries/simple.d.ts +1 -1
  35. package/dist/queries/simple.js +3 -3
  36. package/dist/query-store/__tests__/query-store.test.d.ts +1 -0
  37. package/dist/query-store/{query-store.test.js → __tests__/query-store.test.js} +33 -3
  38. package/dist/query-store/query-store.d.ts +6 -4
  39. package/dist/query-store/query-store.js +12 -3
  40. package/package.json +5 -4
  41. /package/dist/{query-store/query-store.test.d.ts → event-store/interface.js} +0 -0
@@ -0,0 +1,49 @@
1
+ import { verifyEvent } from "nostr-tools";
2
+ import { getHiddenContent, isHiddenContentLocked, unlockHiddenContent } from "./hidden-content.js";
3
+ import { getOrComputeCachedValue } from "./cache.js";
4
+ export const GiftWrapSealSymbol = Symbol.for("gift-wrap-seal");
5
+ export const GiftWrapEventSymbol = Symbol.for("gift-wrap-event");
6
+ /** Returns the unsigned seal event in a gift-wrap event */
7
+ export function getGiftWrapSeal(gift) {
8
+ if (isHiddenContentLocked(gift))
9
+ return undefined;
10
+ return getOrComputeCachedValue(gift, GiftWrapSealSymbol, () => {
11
+ const plaintext = getHiddenContent(gift);
12
+ if (!plaintext)
13
+ throw new Error("Gift-wrap is locked");
14
+ const seal = JSON.parse(plaintext);
15
+ // verify the seal is valid
16
+ verifyEvent(seal);
17
+ return seal;
18
+ });
19
+ }
20
+ /** Returns the unsigned event in the gift-wrap seal */
21
+ export function getGiftWrapEvent(gift) {
22
+ if (isHiddenContentLocked(gift))
23
+ return undefined;
24
+ return getOrComputeCachedValue(gift, GiftWrapEventSymbol, () => {
25
+ const seal = getGiftWrapSeal(gift);
26
+ if (!seal)
27
+ throw new Error("Gift is locked");
28
+ const plaintext = getHiddenContent(seal);
29
+ if (!plaintext)
30
+ throw new Error("Gift-wrap seal is locked");
31
+ const event = JSON.parse(plaintext);
32
+ if (event.pubkey !== seal.pubkey)
33
+ throw new Error("Seal author does not match content");
34
+ return event;
35
+ });
36
+ }
37
+ /** Returns if a gift-wrap event or gift-wrap seal is locked */
38
+ export function isGiftWrapLocked(gift) {
39
+ return isHiddenContentLocked(gift) || isHiddenContentLocked(getGiftWrapSeal(gift));
40
+ }
41
+ /** Unlocks and returns the unsigned seal event in a gift-wrap */
42
+ export async function unlockGiftWrap(gift, signer) {
43
+ if (isHiddenContentLocked(gift))
44
+ await unlockHiddenContent(gift, signer);
45
+ const seal = getGiftWrapSeal(gift);
46
+ if (isHiddenContentLocked(seal))
47
+ await unlockHiddenContent(seal, signer);
48
+ return getGiftWrapEvent(gift);
49
+ }
@@ -0,0 +1,48 @@
1
+ export declare const HiddenContentSymbol: unique symbol;
2
+ export type HiddenContentSigner = {
3
+ nip04?: {
4
+ encrypt: (pubkey: string, plaintext: string) => Promise<string> | string;
5
+ decrypt: (pubkey: string, ciphertext: string) => Promise<string> | string;
6
+ };
7
+ nip44?: {
8
+ encrypt: (pubkey: string, plaintext: string) => Promise<string> | string;
9
+ decrypt: (pubkey: string, ciphertext: string) => Promise<string> | string;
10
+ };
11
+ };
12
+ /** Various event kinds that can have encrypted tags in their content and which encryption method they use */
13
+ export declare const EventContentEncryptionMethod: Record<number, "nip04" | "nip44">;
14
+ /** Sets the encryption method that is used for the contents of a specific event kind */
15
+ export declare function setEventContentEncryptionMethod(kind: number, method: "nip04" | "nip44"): void;
16
+ /** Checks if an event can have hidden content */
17
+ export declare function canHaveHiddenContent(kind: number): boolean;
18
+ /** Checks if an event has hidden content */
19
+ export declare function hasHiddenContent<T extends {
20
+ kind: number;
21
+ content: string;
22
+ }>(event: T): boolean;
23
+ /** Returns the hidden tags for an event if they are unlocked */
24
+ export declare function getHiddenContent<T extends object>(event: T): string | undefined;
25
+ /** Checks if the hidden tags are locked */
26
+ export declare function isHiddenContentLocked<T extends object>(event: T): boolean;
27
+ /** Returns either nip04 or nip44 encryption methods depending on event kind */
28
+ export declare function getHiddenContentEncryptionMethods(kind: number, signer: HiddenContentSigner): {
29
+ encrypt: (pubkey: string, plaintext: string) => Promise<string> | string;
30
+ decrypt: (pubkey: string, ciphertext: string) => Promise<string> | string;
31
+ } | {
32
+ encrypt: (pubkey: string, plaintext: string) => Promise<string> | string;
33
+ decrypt: (pubkey: string, ciphertext: string) => Promise<string> | string;
34
+ };
35
+ export type HiddenContentEvent = {
36
+ kind: number;
37
+ pubkey: string;
38
+ content: string;
39
+ };
40
+ /**
41
+ * Unlocks the encrypted content in an event
42
+ * @param event The event with content to decrypt
43
+ * @param signer A signer to use to decrypt the tags
44
+ * @throws
45
+ */
46
+ export declare function unlockHiddenContent<T extends HiddenContentEvent>(event: T, signer: HiddenContentSigner): Promise<string>;
47
+ /** Removes the unencrypted hidden content on an event */
48
+ export declare function lockHiddenContent<T extends object>(event: T): void;
@@ -0,0 +1,88 @@
1
+ import * as kinds from "nostr-tools/kinds";
2
+ import { GROUPS_LIST_KIND } from "./groups.js";
3
+ import { getParentEventStore, isEvent } from "./event.js";
4
+ export const HiddenContentSymbol = Symbol.for("hidden-content");
5
+ /** Various event kinds that can have encrypted tags in their content and which encryption method they use */
6
+ export const EventContentEncryptionMethod = {
7
+ // NIP-60 wallet
8
+ 17375: "nip44",
9
+ 375: "nip44",
10
+ 7375: "nip44",
11
+ 7376: "nip44",
12
+ // DMs
13
+ [kinds.EncryptedDirectMessage]: "nip04",
14
+ // Gift wraps
15
+ [kinds.GiftWrap]: "nip44",
16
+ // NIP-51 lists
17
+ [kinds.BookmarkList]: "nip04",
18
+ [kinds.InterestsList]: "nip04",
19
+ [kinds.Mutelist]: "nip04",
20
+ [kinds.CommunitiesList]: "nip04",
21
+ [kinds.PublicChatsList]: "nip04",
22
+ [kinds.SearchRelaysList]: "nip04",
23
+ [GROUPS_LIST_KIND]: "nip04",
24
+ // NIP-51 sets
25
+ [kinds.Bookmarksets]: "nip04",
26
+ [kinds.Relaysets]: "nip04",
27
+ [kinds.Followsets]: "nip04",
28
+ [kinds.Curationsets]: "nip04",
29
+ [kinds.Interestsets]: "nip04",
30
+ };
31
+ /** Sets the encryption method that is used for the contents of a specific event kind */
32
+ export function setEventContentEncryptionMethod(kind, method) {
33
+ EventContentEncryptionMethod[kind] = method;
34
+ }
35
+ /** Checks if an event can have hidden content */
36
+ export function canHaveHiddenContent(kind) {
37
+ return EventContentEncryptionMethod[kind] !== undefined;
38
+ }
39
+ /** Checks if an event has hidden content */
40
+ export function hasHiddenContent(event) {
41
+ return canHaveHiddenContent(event.kind) && event.content.length > 0;
42
+ }
43
+ /** Returns the hidden tags for an event if they are unlocked */
44
+ export function getHiddenContent(event) {
45
+ return Reflect.get(event, HiddenContentSymbol);
46
+ }
47
+ /** Checks if the hidden tags are locked */
48
+ export function isHiddenContentLocked(event) {
49
+ return Reflect.has(event, HiddenContentSymbol) === false;
50
+ }
51
+ /** Returns either nip04 or nip44 encryption methods depending on event kind */
52
+ export function getHiddenContentEncryptionMethods(kind, signer) {
53
+ const method = EventContentEncryptionMethod[kind];
54
+ const encryption = signer[method];
55
+ if (!encryption)
56
+ throw new Error(`Signer does not support ${method} encryption`);
57
+ return encryption;
58
+ }
59
+ /**
60
+ * Unlocks the encrypted content in an event
61
+ * @param event The event with content to decrypt
62
+ * @param signer A signer to use to decrypt the tags
63
+ * @throws
64
+ */
65
+ export async function unlockHiddenContent(event, signer) {
66
+ if (!canHaveHiddenContent(event.kind))
67
+ throw new Error("Event kind does not support hidden content");
68
+ const encryption = getHiddenContentEncryptionMethods(event.kind, signer);
69
+ const plaintext = await encryption.decrypt(event.pubkey, event.content);
70
+ Reflect.set(event, HiddenContentSymbol, plaintext);
71
+ // if the event has been added to an event store, notify it
72
+ if (isEvent(event)) {
73
+ const eventStore = getParentEventStore(event);
74
+ if (eventStore)
75
+ eventStore.update(event);
76
+ }
77
+ return plaintext;
78
+ }
79
+ /** Removes the unencrypted hidden content on an event */
80
+ export function lockHiddenContent(event) {
81
+ Reflect.deleteProperty(event, HiddenContentSymbol);
82
+ // if the event has been added to an event store, notify it
83
+ if (isEvent(event)) {
84
+ const eventStore = getParentEventStore(event);
85
+ if (eventStore)
86
+ eventStore.update(event);
87
+ }
88
+ }
@@ -1,28 +1,18 @@
1
- import { EventTemplate, NostrEvent } from "nostr-tools";
2
- import { EventStore } from "../event-store/event-store.js";
3
- export type HiddenTagsSigner = {
4
- nip04?: {
5
- encrypt: (pubkey: string, plaintext: string) => Promise<string> | string;
6
- decrypt: (pubkey: string, ciphertext: string) => Promise<string> | string;
7
- };
8
- nip44?: {
9
- encrypt: (pubkey: string, plaintext: string) => Promise<string> | string;
10
- decrypt: (pubkey: string, ciphertext: string) => Promise<string> | string;
11
- };
12
- };
1
+ import { HiddenContentEvent, HiddenContentSigner } from "./hidden-content.js";
13
2
  export declare const HiddenTagsSymbol: unique symbol;
14
- /** Various event kinds that can have encrypted tags in their content and which encryption method they use */
15
- export declare const EventEncryptionMethod: Record<number, "nip04" | "nip44">;
16
3
  /** Checks if an event can have hidden tags */
17
4
  export declare function canHaveHiddenTags(kind: number): boolean;
18
5
  /** Checks if an event has hidden tags */
19
- export declare function hasHiddenTags(event: NostrEvent | EventTemplate): boolean;
6
+ export declare function hasHiddenTags<T extends {
7
+ content: string;
8
+ kind: number;
9
+ }>(event: T): boolean;
20
10
  /** Returns the hidden tags for an event if they are unlocked */
21
- export declare function getHiddenTags(event: NostrEvent | EventTemplate): string[][] | undefined;
11
+ export declare function getHiddenTags<T extends object>(event: T): string[][] | undefined;
22
12
  /** Checks if the hidden tags are locked */
23
- export declare function isHiddenTagsLocked(event: NostrEvent): boolean;
13
+ export declare function isHiddenTagsLocked<T extends object>(event: T): boolean;
24
14
  /** Returns either nip04 or nip44 encryption method depending on list kind */
25
- export declare function getListEncryptionMethods(kind: number, signer: HiddenTagsSigner): {
15
+ export declare function getHiddenTagsEncryptionMethods(kind: number, signer: HiddenContentSigner): {
26
16
  encrypt: (pubkey: string, plaintext: string) => Promise<string> | string;
27
17
  decrypt: (pubkey: string, ciphertext: string) => Promise<string> | string;
28
18
  } | {
@@ -36,13 +26,5 @@ export declare function getListEncryptionMethods(kind: number, signer: HiddenTag
36
26
  * @param store An optional EventStore to notify about the update
37
27
  * @throws
38
28
  */
39
- export declare function unlockHiddenTags<T extends {
40
- kind: number;
41
- pubkey: string;
42
- content: string;
43
- }>(event: T, signer: HiddenTagsSigner, store?: EventStore): Promise<T>;
44
- /**
45
- * Override the hidden tags in an event
46
- * @throws
47
- */
48
- export declare function overrideHiddenTags(event: NostrEvent, hidden: string[][], signer: HiddenTagsSigner): Promise<EventTemplate>;
29
+ export declare function unlockHiddenTags<T extends HiddenContentEvent>(event: T, signer: HiddenContentSigner): Promise<string[][]>;
30
+ export declare function lockHiddenTags<T extends object>(event: T): void;
@@ -1,30 +1,9 @@
1
- import { kinds } from "nostr-tools";
2
- import { GROUPS_LIST_KIND } from "./groups.js";
3
- import { unixNow } from "./time.js";
4
- import { isEvent } from "./event.js";
1
+ import { canHaveHiddenContent, getHiddenContent, getHiddenContentEncryptionMethods, isHiddenContentLocked, lockHiddenContent, unlockHiddenContent, } from "./hidden-content.js";
2
+ import { getOrComputeCachedValue } from "./cache.js";
5
3
  export const HiddenTagsSymbol = Symbol.for("hidden-tags");
6
- /** Various event kinds that can have encrypted tags in their content and which encryption method they use */
7
- export const EventEncryptionMethod = {
8
- // NIP-60 wallet
9
- 37375: "nip44",
10
- // NIP-51 lists
11
- [kinds.BookmarkList]: "nip04",
12
- [kinds.InterestsList]: "nip04",
13
- [kinds.Mutelist]: "nip04",
14
- [kinds.CommunitiesList]: "nip04",
15
- [kinds.PublicChatsList]: "nip04",
16
- [kinds.SearchRelaysList]: "nip04",
17
- [GROUPS_LIST_KIND]: "nip04",
18
- // NIP-51 sets
19
- [kinds.Bookmarksets]: "nip04",
20
- [kinds.Relaysets]: "nip04",
21
- [kinds.Followsets]: "nip04",
22
- [kinds.Curationsets]: "nip04",
23
- [kinds.Interestsets]: "nip04",
24
- };
25
4
  /** Checks if an event can have hidden tags */
26
5
  export function canHaveHiddenTags(kind) {
27
- return EventEncryptionMethod[kind] !== undefined;
6
+ return canHaveHiddenContent(kind);
28
7
  }
29
8
  /** Checks if an event has hidden tags */
30
9
  export function hasHiddenTags(event) {
@@ -32,19 +11,24 @@ export function hasHiddenTags(event) {
32
11
  }
33
12
  /** Returns the hidden tags for an event if they are unlocked */
34
13
  export function getHiddenTags(event) {
35
- return Reflect.get(event, HiddenTagsSymbol);
14
+ if (isHiddenTagsLocked(event))
15
+ return undefined;
16
+ return getOrComputeCachedValue(event, HiddenTagsSymbol, () => {
17
+ const plaintext = getHiddenContent(event);
18
+ const parsed = JSON.parse(plaintext);
19
+ if (!Array.isArray(parsed))
20
+ throw new Error("Content is not an array of tags");
21
+ // Convert array to tags array string[][]
22
+ return parsed.filter((t) => Array.isArray(t)).map((t) => t.map((v) => String(v)));
23
+ });
36
24
  }
37
25
  /** Checks if the hidden tags are locked */
38
26
  export function isHiddenTagsLocked(event) {
39
- return hasHiddenTags(event) && getHiddenTags(event) === undefined;
27
+ return isHiddenContentLocked(event);
40
28
  }
41
29
  /** Returns either nip04 or nip44 encryption method depending on list kind */
42
- export function getListEncryptionMethods(kind, signer) {
43
- const method = EventEncryptionMethod[kind];
44
- const encryption = signer[method];
45
- if (!encryption)
46
- throw new Error(`Signer does not support ${method} encryption`);
47
- return encryption;
30
+ export function getHiddenTagsEncryptionMethods(kind, signer) {
31
+ return getHiddenContentEncryptionMethods(kind, signer);
48
32
  }
49
33
  /**
50
34
  * Decrypts the private list
@@ -53,34 +37,15 @@ export function getListEncryptionMethods(kind, signer) {
53
37
  * @param store An optional EventStore to notify about the update
54
38
  * @throws
55
39
  */
56
- export async function unlockHiddenTags(event, signer, store) {
40
+ export async function unlockHiddenTags(event, signer) {
57
41
  if (!canHaveHiddenTags(event.kind))
58
42
  throw new Error("Event kind does not support hidden tags");
59
- const encryption = getListEncryptionMethods(event.kind, signer);
60
- const plaintext = await encryption.decrypt(event.pubkey, event.content);
61
- const parsed = JSON.parse(plaintext);
62
- if (!Array.isArray(parsed))
63
- throw new Error("Content is not an array of tags");
64
- // Convert array to tags array string[][]
65
- const tags = parsed.filter((t) => Array.isArray(t)).map((t) => t.map((v) => String(v)));
66
- Reflect.set(event, HiddenTagsSymbol, tags);
67
- if (store && isEvent(event))
68
- store.update(event);
69
- return event;
43
+ // unlock hidden content is needed
44
+ if (isHiddenContentLocked(event))
45
+ await unlockHiddenContent(event, signer);
46
+ return getHiddenTags(event);
70
47
  }
71
- /**
72
- * Override the hidden tags in an event
73
- * @throws
74
- */
75
- export async function overrideHiddenTags(event, hidden, signer) {
76
- if (!canHaveHiddenTags(event.kind))
77
- throw new Error("Event kind does not support hidden tags");
78
- const encryption = getListEncryptionMethods(event.kind, signer);
79
- const ciphertext = await encryption.encrypt(event.pubkey, JSON.stringify(hidden));
80
- return {
81
- kind: event.kind,
82
- content: ciphertext,
83
- created_at: unixNow(),
84
- tags: event.tags,
85
- };
48
+ export function lockHiddenTags(event) {
49
+ Reflect.deleteProperty(event, HiddenTagsSymbol);
50
+ lockHiddenContent(event);
86
51
  }
@@ -7,14 +7,17 @@ export * from "./comment.js";
7
7
  export * from "./contacts.js";
8
8
  export * from "./content.js";
9
9
  export * from "./delete.js";
10
+ export * from "./direct-messages.js";
10
11
  export * from "./dns-identity.js";
11
12
  export * from "./emoji.js";
12
13
  export * from "./event.js";
13
14
  export * from "./external-id.js";
14
15
  export * from "./file-metadata.js";
15
16
  export * from "./filter.js";
17
+ export * from "./gift-wraps.js";
16
18
  export * from "./groups.js";
17
19
  export * from "./hashtag.js";
20
+ export * from "./hidden-content.js";
18
21
  export * from "./hidden-tags.js";
19
22
  export * from "./json.js";
20
23
  export * from "./lists.js";
@@ -7,14 +7,17 @@ export * from "./comment.js";
7
7
  export * from "./contacts.js";
8
8
  export * from "./content.js";
9
9
  export * from "./delete.js";
10
+ export * from "./direct-messages.js";
10
11
  export * from "./dns-identity.js";
11
12
  export * from "./emoji.js";
12
13
  export * from "./event.js";
13
14
  export * from "./external-id.js";
14
15
  export * from "./file-metadata.js";
15
16
  export * from "./filter.js";
17
+ export * from "./gift-wraps.js";
16
18
  export * from "./groups.js";
17
19
  export * from "./hashtag.js";
20
+ export * from "./hidden-content.js";
18
21
  export * from "./hidden-tags.js";
19
22
  export * from "./json.js";
20
23
  export * from "./lists.js";
@@ -7,6 +7,7 @@ export type Mutes = {
7
7
  hashtags: Set<string>;
8
8
  words: Set<string>;
9
9
  };
10
+ /** Parses mute tags */
10
11
  export declare function parseMutedTags(tags: string[][]): Mutes;
11
12
  /** Returns muted things */
12
13
  export declare function getMutedThings(mute: NostrEvent): Mutes;
@@ -3,6 +3,7 @@ import { getOrComputeCachedValue } from "./cache.js";
3
3
  import { getHiddenTags } from "./hidden-tags.js";
4
4
  export const MutePublicSymbol = Symbol.for("mute-public");
5
5
  export const MuteHiddenSymbol = Symbol.for("mute-hidden");
6
+ /** Parses mute tags */
6
7
  export function parseMutedTags(tags) {
7
8
  const pubkeys = new Set(tags.filter(isPTag).map((t) => t[1]));
8
9
  const threads = new Set(tags.filter(isETag).map((t) => t[1]));
@@ -12,7 +13,7 @@ export function parseMutedTags(tags) {
12
13
  }
13
14
  /** Returns muted things */
14
15
  export function getMutedThings(mute) {
15
- return getOrComputeCachedValue(mute, MutePublicSymbol, (e) => parseMutedTags(e.tags));
16
+ return getOrComputeCachedValue(mute, MutePublicSymbol, () => parseMutedTags(mute.tags));
16
17
  }
17
18
  /** Returns the hidden muted content if the event is unlocked */
18
19
  export function getHiddenMutedThings(mute) {
@@ -0,0 +1,4 @@
1
+ /** Gets the hex pubkey from any nip-19 encoded string */
2
+ export declare function normalizeToPubkey(str: string): string;
3
+ /** Converts hex to nsec strings into Uint8 secret keys */
4
+ export declare function normalizeToSecretKey(str: string): Uint8Array;
@@ -0,0 +1,27 @@
1
+ import { nip19 } from "nostr-tools";
2
+ import { hexToBytes } from "@noble/hashes/utils";
3
+ import { isHexKey } from "./string.js";
4
+ import { getPubkeyFromDecodeResult } from "./pointers.js";
5
+ /** Gets the hex pubkey from any nip-19 encoded string */
6
+ export function normalizeToPubkey(str) {
7
+ if (isHexKey(str))
8
+ return str;
9
+ else {
10
+ const decode = nip19.decode(str);
11
+ const pubkey = getPubkeyFromDecodeResult(decode);
12
+ if (!pubkey)
13
+ throw new Error(`Cant find pubkey in ${decode.type}`);
14
+ return pubkey;
15
+ }
16
+ }
17
+ /** Converts hex to nsec strings into Uint8 secret keys */
18
+ export function normalizeToSecretKey(str) {
19
+ if (isHexKey(str))
20
+ return hexToBytes(str);
21
+ else {
22
+ const decode = nip19.decode(str);
23
+ if (decode.type !== "nsec")
24
+ throw new Error(`Cant get secret key from ${decode.type}`);
25
+ return decode.data;
26
+ }
27
+ }
@@ -1,4 +1,5 @@
1
1
  import { MonoTypeOperatorFunction } from "rxjs";
2
2
  import { NostrEvent } from "nostr-tools";
3
- import { Database } from "../event-store/database.js";
4
- export declare function claimLatest(database: Database): MonoTypeOperatorFunction<NostrEvent | undefined>;
3
+ import { type Database } from "../event-store/database.js";
4
+ /** An operator that claims the latest event with the database */
5
+ export declare function claimLatest<T extends NostrEvent | undefined>(database: Database): MonoTypeOperatorFunction<T>;
@@ -1,4 +1,5 @@
1
1
  import { finalize, tap } from "rxjs";
2
+ /** An operator that claims the latest event with the database */
2
3
  export function claimLatest(database) {
3
4
  return (source) => {
4
5
  let latest = undefined;
@@ -12,7 +13,7 @@ export function claimLatest(database) {
12
13
  // update state
13
14
  latest = event;
14
15
  }), finalize(() => {
15
- // late claim
16
+ // remove latest claim
16
17
  if (latest)
17
18
  database.removeClaim(latest, source);
18
19
  }));
@@ -0,0 +1,3 @@
1
+ import { OperatorFunction } from "rxjs";
2
+ /** if a synchronous value is not emitted, default is emitted */
3
+ export declare function withImmediateValueOrDefault<Value, Default extends unknown = unknown>(defaultValue: Default): OperatorFunction<Value, Value | Default>;
@@ -0,0 +1,19 @@
1
+ import { Observable } from "rxjs";
2
+ /** if a synchronous value is not emitted, default is emitted */
3
+ export function withImmediateValueOrDefault(defaultValue) {
4
+ return (source) => new Observable((observer) => {
5
+ let seen = false;
6
+ const sub = source.subscribe({
7
+ next: (v) => {
8
+ seen = true;
9
+ observer.next(v);
10
+ },
11
+ error: (err) => observer.error(err),
12
+ complete: () => observer.complete(),
13
+ });
14
+ // if a value is not emitted sync, emit default
15
+ if (!seen)
16
+ observer.next(defaultValue);
17
+ return sub;
18
+ });
19
+ }
@@ -5,7 +5,7 @@ import { isHiddenTagsLocked } from "../helpers/hidden-tags.js";
5
5
  export function UserMuteQuery(pubkey) {
6
6
  return {
7
7
  key: pubkey,
8
- run: (store) => store.replaceable(kinds.Mutelist, pubkey).pipe(map((event) => event && getMutedThings(event))),
8
+ run: (event) => event.replaceable(kinds.Mutelist, pubkey).pipe(map((event) => event && getMutedThings(event))),
9
9
  };
10
10
  }
11
11
  export function UserHiddenMuteQuery(pubkey) {
@@ -7,7 +7,7 @@ export declare function MultipleEventsQuery(ids: string[]): Query<Record<string,
7
7
  /** Creates a Query returning the latest version of a replaceable event */
8
8
  export declare function ReplaceableQuery(kind: number, pubkey: string, d?: string): Query<NostrEvent | undefined>;
9
9
  /** Creates a Query that returns an array of sorted events matching the filters */
10
- export declare function TimelineQuery(filters: Filter | Filter[], keepOldVersions?: boolean): Query<NostrEvent[]>;
10
+ export declare function TimelineQuery(filters: Filter | Filter[], includeOldVersion?: boolean): Query<NostrEvent[]>;
11
11
  /** Creates a Query that returns a directory of events by their UID */
12
12
  export declare function ReplaceableSetQuery(pointers: {
13
13
  kind: number;
@@ -22,11 +22,11 @@ export function ReplaceableQuery(kind, pubkey, d) {
22
22
  };
23
23
  }
24
24
  /** Creates a Query that returns an array of sorted events matching the filters */
25
- export function TimelineQuery(filters, keepOldVersions) {
25
+ export function TimelineQuery(filters, includeOldVersion) {
26
26
  filters = Array.isArray(filters) ? filters : [filters];
27
27
  return {
28
- key: hash_sum(filters) + (keepOldVersions ? "-history" : ""),
29
- run: (events) => events.timeline(filters, keepOldVersions),
28
+ key: hash_sum(filters) + (includeOldVersion ? "-history" : ""),
29
+ run: (events) => events.timeline(filters, includeOldVersion),
30
30
  };
31
31
  }
32
32
  /** Creates a Query that returns a directory of events by their UID */
@@ -0,0 +1 @@
1
+ export {};
@@ -1,7 +1,9 @@
1
1
  import { describe, it, expect, beforeEach } from "vitest";
2
- import { EventStore } from "../event-store/event-store.js";
3
- import { QueryStore } from "./query-store.js";
4
- import { ProfileQuery } from "../queries/profile.js";
2
+ import { subscribeSpyTo } from "@hirez_io/observer-spy";
3
+ import { EventStore } from "../../event-store/event-store.js";
4
+ import { QueryStore } from "../query-store.js";
5
+ import { ProfileQuery } from "../../queries/profile.js";
6
+ import { SingleEventQuery } from "../../queries/simple.js";
5
7
  let eventStore;
6
8
  let queryStore;
7
9
  const event = {
@@ -17,6 +19,34 @@ beforeEach(() => {
17
19
  eventStore = new EventStore();
18
20
  queryStore = new QueryStore(eventStore);
19
21
  });
22
+ describe("createQuery", () => {
23
+ it("should emit synchronous value if it exists", () => {
24
+ let value = undefined;
25
+ eventStore.add(event);
26
+ queryStore.createQuery(ProfileQuery, event.pubkey).subscribe((v) => (value = v));
27
+ expect(value).not.toBe(undefined);
28
+ });
29
+ it("should not emit undefined if value exists", () => {
30
+ eventStore.add(event);
31
+ const spy = subscribeSpyTo(queryStore.createQuery(SingleEventQuery, event.id));
32
+ expect(spy.getValues()).toEqual([event]);
33
+ });
34
+ it("should emit synchronous undefined if value does not exists", () => {
35
+ let value = 0;
36
+ queryStore.createQuery(ProfileQuery, event.pubkey).subscribe((v) => {
37
+ value = v;
38
+ });
39
+ expect(value).not.toBe(0);
40
+ expect(value).toBe(undefined);
41
+ });
42
+ it("should share latest value", () => {
43
+ eventStore.add(event);
44
+ const spy = subscribeSpyTo(queryStore.createQuery(SingleEventQuery, event.id));
45
+ const spy2 = subscribeSpyTo(queryStore.createQuery(SingleEventQuery, event.id));
46
+ expect(spy.getValues()).toEqual([event]);
47
+ expect(spy2.getValues()).toEqual([event]);
48
+ });
49
+ });
20
50
  describe("executeQuery", () => {
21
51
  it("should resolve when value is already present", async () => {
22
52
  eventStore.add(event);
@@ -1,19 +1,19 @@
1
1
  import { Observable } from "rxjs";
2
2
  import { Filter, NostrEvent } from "nostr-tools";
3
3
  import type { AddressPointer, EventPointer } from "nostr-tools/nip19";
4
- import { EventStore } from "../event-store/event-store.js";
4
+ import { IEventStore } from "../event-store/interface.js";
5
5
  import * as Queries from "../queries/index.js";
6
6
  export type Query<T extends unknown> = {
7
7
  /** A unique key for this query. this is used to detect duplicate queries */
8
8
  key: string;
9
9
  /** The meat of the query, this should return an Observables that subscribes to the eventStore in some way */
10
- run: (events: EventStore, store: QueryStore) => Observable<T>;
10
+ run: (events: IEventStore, store: QueryStore) => Observable<T>;
11
11
  };
12
12
  export type QueryConstructor<T extends unknown, Args extends Array<any>> = (...args: Args) => Query<T>;
13
13
  export declare class QueryStore {
14
14
  static Queries: typeof Queries;
15
- store: EventStore;
16
- constructor(store: EventStore);
15
+ store: IEventStore;
16
+ constructor(store: IEventStore);
17
17
  /** A directory of all active queries */
18
18
  queries: Map<QueryConstructor<any, any[]>, Map<string, Observable<any>>>;
19
19
  /** How long a query should be kept "warm" while nothing is subscribed to it */
@@ -45,6 +45,8 @@ export declare class QueryStore {
45
45
  inboxes: string[];
46
46
  outboxes: string[];
47
47
  } | undefined>;
48
+ /** Creates a query for a users blossom servers */
49
+ blossomServers(pubkey: string): Observable<URL[] | undefined>;
48
50
  /** Creates a ThreadQuery */
49
51
  thread(root: string | EventPointer | AddressPointer): Observable<Queries.Thread | undefined>;
50
52
  }