80 lines
2.5 KiB
JavaScript
80 lines
2.5 KiB
JavaScript
import { ref } from "vue";
|
|
import { parse } from "/app/node_modules/cookie-es/dist/index.mjs";
|
|
import { getRequestHeader, setCookie, getCookie, deleteCookie } from "/app/node_modules/h3/dist/index.mjs";
|
|
import destr from "/app/node_modules/destr/dist/index.mjs";
|
|
import { isEqual } from "/app/node_modules/ohash/dist/index.mjs";
|
|
import { klona } from "/app/node_modules/klona/dist/index.mjs";
|
|
import { a as useNuxtApp } from "../server.mjs";
|
|
function useRequestEvent(nuxtApp) {
|
|
nuxtApp ||= useNuxtApp();
|
|
return nuxtApp.ssrContext?.event;
|
|
}
|
|
const CookieDefaults = {
|
|
path: "/",
|
|
watch: true,
|
|
decode: (val) => {
|
|
const decoded = decodeURIComponent(val);
|
|
const parsed = destr(decoded);
|
|
if (typeof parsed === "number" && (!Number.isFinite(parsed) || String(parsed) !== decoded)) {
|
|
return decoded;
|
|
}
|
|
return parsed;
|
|
},
|
|
encode: (val) => encodeURIComponent(typeof val === "string" ? val : JSON.stringify(val))
|
|
};
|
|
function useCookie(name, _opts) {
|
|
const opts = { ...CookieDefaults, ..._opts };
|
|
opts.filter ??= (key) => key === name;
|
|
const cookies = readRawCookies(opts) || {};
|
|
let delay;
|
|
if (opts.maxAge !== void 0) {
|
|
delay = opts.maxAge * 1e3;
|
|
} else if (opts.expires) {
|
|
delay = opts.expires.getTime() - Date.now();
|
|
}
|
|
const hasExpired = delay !== void 0 && delay <= 0;
|
|
const cookieValue = klona(hasExpired ? void 0 : cookies[name] ?? opts.default?.());
|
|
const cookie = ref(cookieValue);
|
|
{
|
|
const nuxtApp = useNuxtApp();
|
|
const writeFinalCookieValue = () => {
|
|
if (opts.readonly || isEqual(cookie.value, cookies[name])) {
|
|
return;
|
|
}
|
|
nuxtApp._cookies ||= {};
|
|
if (name in nuxtApp._cookies) {
|
|
if (isEqual(cookie.value, nuxtApp._cookies[name])) {
|
|
return;
|
|
}
|
|
}
|
|
nuxtApp._cookies[name] = cookie.value;
|
|
writeServerCookie(useRequestEvent(nuxtApp), name, cookie.value, opts);
|
|
};
|
|
const unhook = nuxtApp.hooks.hookOnce("app:rendered", writeFinalCookieValue);
|
|
nuxtApp.hooks.hookOnce("app:error", () => {
|
|
unhook();
|
|
return writeFinalCookieValue();
|
|
});
|
|
}
|
|
return cookie;
|
|
}
|
|
function readRawCookies(opts = {}) {
|
|
{
|
|
return parse(getRequestHeader(useRequestEvent(), "cookie") || "", opts);
|
|
}
|
|
}
|
|
function writeServerCookie(event, name, value, opts = {}) {
|
|
if (event) {
|
|
if (value !== null && value !== void 0) {
|
|
return setCookie(event, name, value, opts);
|
|
}
|
|
if (getCookie(event, name) !== void 0) {
|
|
return deleteCookie(event, name, opts);
|
|
}
|
|
}
|
|
}
|
|
export {
|
|
useCookie as u
|
|
};
|
|
//# sourceMappingURL=cookie-CWIsZYm7.js.map
|