-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwarpcast.ts
90 lines (79 loc) · 2.42 KB
/
warpcast.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import validator from 'validator';
const isUrl = validator.isURL;
interface WarpcastComposeOptions {
text: string;
embeds?: string[];
parentCastHash?: string;
channelKey?: string;
}
const hashPattern = /^0x[a-fA-F0-9]{40}$/; // regex pattern for hash validation
/**
* Methods to generate a Warpcast composer URL with the given options,
* docs at https://docs.farcaster.xyz/reference/warpcast/cast-composer-intents
*
*/
export class WarpcastUrlBuilder {
private static readonly COMPOSER_BASE_URL = 'https://warpcast.com/~/compose';
/**
* @param options.text - The text of the cast
*
* @param options.embeds - The embeds to include in the cast (max 2), must be valid URLs
*
* @param options.parentCastHash - The parent cast hash for replies,
* `/^0x[a-fA-F0-9]{40}$/`,
* overrides `options.channelKey`
*
* @param options.channelKey - The name of the channel to post to
*
* @returns The composer URL
*/
static composerUrl(options: WarpcastComposeOptions): string {
const params = new URLSearchParams();
params.append('text', options.text);
if (options.embeds?.length) {
if (options.embeds?.length > 2) {
throw new Error('Warpcast does not support more than 2 embeds');
}
options.embeds.forEach((embed) => {
if (
!isUrl(embed, {
require_protocol: true,
protocols: ['http', 'https'],
})
) {
throw new Error('Embed strings must be valid URLs');
}
return params.append('embeds[]', embed);
});
}
if (options.channelKey) {
params.append('channelKey', options.channelKey);
}
if (options.parentCastHash) {
if (!hashPattern.test(options.parentCastHash)) {
throw new Error('Invalid parent cast hash');
}
params.append('parentCastHash', options.parentCastHash);
}
return `${this.COMPOSER_BASE_URL}?${params.toString()}`;
}
/**
* @param fid - The fid of the user
*
* @returns The profile URL
*/
static profileUrl(fid: number): string {
return `https://warpcast.com/~/profiles/${fid.toString()}`;
}
/**
* @param hash - The hash of the cast, `/^0x[a-fA-F0-9]{40}$/`
*
* @returns The warpcast conversation URL
*/
static castUrlByHash(hash: string): string {
if (!hashPattern.test(hash)) {
throw new Error('Invalid cast hash');
}
return `https://warpcast.com/~/conversations/${hash}`;
}
}