forked from
slices.network/slices
Highly ambitious ATProtocol AppView service and sdks
1import type { CookieOptions } from "./types.ts";
2
3export function parseCookie(cookieString: string): Record<string, string> {
4 const cookies: Record<string, string> = {};
5
6 if (!cookieString) return cookies;
7
8 const pairs = cookieString.split(";");
9
10 for (const pair of pairs) {
11 const [key, ...valueParts] = pair.split("=");
12 const trimmedKey = key?.trim();
13 const value = valueParts.join("=")?.trim();
14
15 if (trimmedKey) {
16 cookies[trimmedKey] = decodeURIComponent(value || "");
17 }
18 }
19
20 return cookies;
21}
22
23export function serializeCookie(
24 name: string,
25 value: string,
26 options: CookieOptions = {}
27): string {
28 const parts = [`${encodeURIComponent(name)}=${encodeURIComponent(value)}`];
29
30 if (options.maxAge !== undefined) {
31 parts.push(`Max-Age=${options.maxAge}`);
32 }
33
34 if (options.domain) {
35 parts.push(`Domain=${options.domain}`);
36 }
37
38 if (options.path) {
39 parts.push(`Path=${options.path}`);
40 }
41
42 if (options.httpOnly) {
43 parts.push("HttpOnly");
44 }
45
46 if (options.secure) {
47 parts.push("Secure");
48 }
49
50 if (options.sameSite) {
51 parts.push(`SameSite=${options.sameSite}`);
52 }
53
54 return parts.join("; ");
55}