Skip to content

Commit

Permalink
Format
Browse files Browse the repository at this point in the history
  • Loading branch information
atk authored and github-actions[bot] committed Sep 1, 2024
1 parent 1966978 commit ee73b0f
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 104 deletions.
184 changes: 82 additions & 102 deletions packages/storage/src/cookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,14 @@ function serializeCookieOptions(options?: CookieOptions) {
if (!options) return "";
const result = Object.entries(options)
.map(([key, value]) => {
const serializedKey: string | undefined =
cookiePropertyMap[key as keyof CookiePropertyTypes];
const serializedKey: string | undefined = cookiePropertyMap[key as keyof CookiePropertyTypes];
if (!serializedKey) return undefined;

if (value instanceof Date)
return `${serializedKey}=${value.toUTCString()}`;
if (typeof value === "boolean")
return value ? `${serializedKey}` : undefined;
if (value instanceof Date) return `${serializedKey}=${value.toUTCString()}`;
if (typeof value === "boolean") return value ? `${serializedKey}` : undefined;
return `${serializedKey}=${value}`;
})
.filter((v) => !!v);
.filter(v => !!v);

return result.length != 0 ? `; ${result.join("; ")}` : "";
}
Expand All @@ -59,19 +56,13 @@ function deserializeCookieOptions(cookie: string, key: string) {

const getRequestHeaders = isServer
? () =>
(
getRequestEvent() as
| (Partial<RequestEvent> & { response?: Response })
| undefined
)?.request?.headers || new Headers()
(getRequestEvent() as (Partial<RequestEvent> & { response?: Response }) | undefined)?.request
?.headers || new Headers()
: () => new Headers();
const getResponseHeaders = isServer
? () =>
(
getRequestEvent() as
| (Partial<RequestEvent> & { response?: Response })
| undefined
)?.response?.headers || new Headers()
(getRequestEvent() as (Partial<RequestEvent> & { response?: Response }) | undefined)?.response
?.headers || new Headers()
: () => new Headers();

/**
Expand All @@ -93,90 +84,79 @@ const getResponseHeaders = isServer
* ```
* Also, you can use its _read and _write properties to change reading and writing
*/
export const cookieStorage: SyncStorageWithOptions<CookieOptions> =
addWithOptionsMethod(
addClearMethod({
_read: isServer
? (options?: CookieOptions) => {
const requestCookies = (
options?.getRequestHeaders?.() || getRequestHeaders()
).get("Cookie");
const responseCookies = (
options?.getResponseHeaders?.() || getResponseHeaders()
).get("Set-Cookie");
const cookies: Record<string, string> = {};
const addCookie = (_: string, key: string, val: string) =>
(cookies[key] = val);
requestCookies?.replace(/(?:^|;)([^=]+)=([^;]+)/g, addCookie);
responseCookies?.replace(/(?:^|, )([^=]+)=([^;]+)/g, addCookie);
return Object.entries(cookies)
.map((keyval) => keyval.join("="))
.join("; ");
}
: () => document.cookie,
_write: isServer
? (key: string, value: string, options?: CookieOptions) => {
const responseHeaders = getResponseHeaders();
const currentCookies =
responseHeaders
.get("Set-Cookie")
?.split(", ")
.filter((cookie) => cookie && !cookie.startsWith(`${key}=`)) ??
[];
responseHeaders.set(
"Set-Cookie",
[
...currentCookies,
`${key}=${value}${serializeCookieOptions(options)}`,
].join(", ")
);
export const cookieStorage: SyncStorageWithOptions<CookieOptions> = addWithOptionsMethod(
addClearMethod({
_read: isServer
? (options?: CookieOptions) => {
const requestCookies = (options?.getRequestHeaders?.() || getRequestHeaders()).get(
"Cookie",
);
const responseCookies = (options?.getResponseHeaders?.() || getResponseHeaders()).get(
"Set-Cookie",
);
const cookies: Record<string, string> = {};
const addCookie = (_: string, key: string, val: string) => (cookies[key] = val);
requestCookies?.replace(/(?:^|;)([^=]+)=([^;]+)/g, addCookie);
responseCookies?.replace(/(?:^|, )([^=]+)=([^;]+)/g, addCookie);
return Object.entries(cookies)
.map(keyval => keyval.join("="))
.join("; ");
}
: () => document.cookie,
_write: isServer
? (key: string, value: string, options?: CookieOptions) => {
const responseHeaders = getResponseHeaders();
const currentCookies =
responseHeaders
.get("Set-Cookie")
?.split(", ")
.filter(cookie => cookie && !cookie.startsWith(`${key}=`)) ?? [];
responseHeaders.set(
"Set-Cookie",
[...currentCookies, `${key}=${value}${serializeCookieOptions(options)}`].join(", "),
);
}
: (key: string, value: string, options?: CookieOptions) => {
document.cookie = `${key}=${value}${serializeCookieOptions(options)}`;
},
getItem: (key: string, options?: CookieOptions) =>
deserializeCookieOptions(cookieStorage._read(options), key),
setItem: (key: string, value: string, options?: CookieOptions) => {
cookieStorage._write(
key,
value.replace(/[\u00c0-\uffff\&;]/g, c => encodeURIComponent(c)),
options,
);
},
removeItem: (key: string, options?: CookieOptions) => {
cookieStorage._write(key, "deleted", {
...options,
expires: new Date(0),
});
},
key: (index: number, options?: CookieOptions) => {
let key: string | null = null;
let count = 0;
cookieStorage
._read(options)
.replace(/(?:^|;)\s*(.+?)\s*=\s*[^;]+/g, (_: string, found: string) => {
if (!key && found && count++ === index) {
key = found;
}
: (key: string, value: string, options?: CookieOptions) => {
document.cookie = `${key}=${value}${serializeCookieOptions(
options
)}`;
},
getItem: (key: string, options?: CookieOptions) =>
deserializeCookieOptions(cookieStorage._read(options), key),
setItem: (key: string, value: string, options?: CookieOptions) => {
cookieStorage._write(key, value.replace(/[\u00c0-\uffff\&;]/g, (c) =>
encodeURIComponent(c)
), options);
},
removeItem: (key: string, options?: CookieOptions) => {
cookieStorage._write(key, "deleted", {
...options,
expires: new Date(0),
return "";
});
},
key: (index: number, options?: CookieOptions) => {
let key: string | null = null;
let count = 0;
cookieStorage
._read(options)
.replace(
/(?:^|;)\s*(.+?)\s*=\s*[^;]+/g,
(_: string, found: string) => {
if (!key && found && count++ === index) {
key = found;
}
return "";
}
);
return key;
},
getLength: (options?: CookieOptions) => {
let length = 0;
cookieStorage
._read(options)
.replace(/(?:^|;)\s*.+?\s*=\s*[^;]+/g, (found: string) => {
length += found ? 1 : 0;
return "";
});
return length;
},
get length() {
return this.getLength();
},
})
);
return key;
},
getLength: (options?: CookieOptions) => {
let length = 0;
cookieStorage._read(options).replace(/(?:^|;)\s*.+?\s*=\s*[^;]+/g, (found: string) => {
length += found ? 1 : 0;
return "";
});
return length;
},
get length() {
return this.getLength();
},
}),
);
4 changes: 2 additions & 2 deletions packages/storage/test/cookies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ describe("cookieStorage", () => {
});
});

it('(de)-serializes utf-8 characters correctly', () => {
it("(de)-serializes utf-8 characters correctly", () => {
const set = vi.spyOn(document, "cookie", "set");
const umlaute = "äöüÄÖÜ"
const umlaute = "äöüÄÖÜ";
cookieStorage.setItem("test4", umlaute);
expect(set).toHaveBeenCalledWith("test4=" + encodeURIComponent(umlaute));
expect(cookieStorage.getItem("test4")).toBe(umlaute);
Expand Down

0 comments on commit ee73b0f

Please sign in to comment.