Files
service-finder/frontend_admin/.output/server/chunks/nitro/nitro.mjs
2026-06-30 08:56:55 +00:00

8106 lines
251 KiB
JavaScript

import process from 'node:process';globalThis._importMeta_=globalThis._importMeta_||{url:"file:///_entry.js",env:process.env};import http, { Server as Server$1 } from 'node:http';
import https, { Server } from 'node:https';
import { EventEmitter } from 'node:events';
import { Buffer as Buffer$1 } from 'node:buffer';
import { promises, existsSync } from 'node:fs';
import { resolve as resolve$1, dirname as dirname$1, join } from 'node:path';
import { createHash } from 'node:crypto';
import { createRouterMatcher } from 'vue-router';
import { fileURLToPath } from 'node:url';
const suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
function jsonParseTransform(key, value) {
if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) {
warnKeyDropped(key);
return;
}
return value;
}
function warnKeyDropped(key) {
console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`);
}
function destr(value, options = {}) {
if (typeof value !== "string") {
return value;
}
if (value[0] === '"' && value[value.length - 1] === '"' && value.indexOf("\\") === -1) {
return value.slice(1, -1);
}
const _value = value.trim();
if (_value.length <= 9) {
switch (_value.toLowerCase()) {
case "true": {
return true;
}
case "false": {
return false;
}
case "undefined": {
return void 0;
}
case "null": {
return null;
}
case "nan": {
return Number.NaN;
}
case "infinity": {
return Number.POSITIVE_INFINITY;
}
case "-infinity": {
return Number.NEGATIVE_INFINITY;
}
}
}
if (!JsonSigRx.test(value)) {
if (options.strict) {
throw new SyntaxError("[destr] Invalid JSON");
}
return value;
}
try {
if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) {
if (options.strict) {
throw new Error("[destr] Possible prototype pollution");
}
return JSON.parse(value, jsonParseTransform);
}
return JSON.parse(value);
} catch (error) {
if (options.strict) {
throw error;
}
return value;
}
}
const HASH_RE = /#/g;
const AMPERSAND_RE = /&/g;
const SLASH_RE = /\//g;
const EQUAL_RE = /=/g;
const IM_RE = /\?/g;
const PLUS_RE = /\+/g;
const ENC_CARET_RE = /%5e/gi;
const ENC_BACKTICK_RE = /%60/gi;
const ENC_PIPE_RE = /%7c/gi;
const ENC_SPACE_RE = /%20/gi;
const ENC_SLASH_RE = /%2f/gi;
const ENC_ENC_SLASH_RE = /%252f/gi;
function encode(text) {
return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
}
function encodeQueryValue(input) {
return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^").replace(SLASH_RE, "%2F");
}
function encodeQueryKey(text) {
return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
}
function encodePath(text) {
return encode(text).replace(HASH_RE, "%23").replace(IM_RE, "%3F").replace(ENC_ENC_SLASH_RE, "%2F").replace(AMPERSAND_RE, "%26").replace(PLUS_RE, "%2B");
}
function decode$2(text = "") {
try {
return decodeURIComponent("" + text);
} catch {
return "" + text;
}
}
function decodePath(text) {
return decode$2(text.replace(ENC_SLASH_RE, "%252F"));
}
function decodeQueryKey(text) {
return decode$2(text.replace(PLUS_RE, " "));
}
function decodeQueryValue(text) {
return decode$2(text.replace(PLUS_RE, " "));
}
function parseQuery(parametersString = "") {
const object = /* @__PURE__ */ Object.create(null);
if (parametersString[0] === "?") {
parametersString = parametersString.slice(1);
}
for (const parameter of parametersString.split("&")) {
const s = parameter.match(/([^=]+)=?(.*)/) || [];
if (s.length < 2) {
continue;
}
const key = decodeQueryKey(s[1]);
if (key === "__proto__" || key === "constructor") {
continue;
}
const value = decodeQueryValue(s[2] || "");
if (object[key] === void 0) {
object[key] = value;
} else if (Array.isArray(object[key])) {
object[key].push(value);
} else {
object[key] = [object[key], value];
}
}
return object;
}
function encodeQueryItem(key, value) {
if (typeof value === "number" || typeof value === "boolean") {
value = String(value);
}
if (!value) {
return encodeQueryKey(key);
}
if (Array.isArray(value)) {
return value.map(
(_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`
).join("&");
}
return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
}
function stringifyQuery(query) {
return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
}
const PROTOCOL_STRICT_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{1,2})/;
const PROTOCOL_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{2})?/;
const PROTOCOL_RELATIVE_REGEX = /^([/\\]\s*){2,}[^/\\]/;
const PROTOCOL_SCRIPT_RE = /^[\s\0]*(blob|data|javascript|vbscript):$/i;
const TRAILING_SLASH_RE = /\/$|\/\?|\/#/;
const JOIN_LEADING_SLASH_RE = /^\.?\//;
function hasProtocol(inputString, opts = {}) {
if (typeof opts === "boolean") {
opts = { acceptRelative: opts };
}
if (opts.strict) {
return PROTOCOL_STRICT_REGEX.test(inputString);
}
return PROTOCOL_REGEX.test(inputString) || (opts.acceptRelative ? PROTOCOL_RELATIVE_REGEX.test(inputString) : false);
}
function isScriptProtocol(protocol) {
return !!protocol && PROTOCOL_SCRIPT_RE.test(protocol);
}
function hasTrailingSlash(input = "", respectQueryAndFragment) {
if (!respectQueryAndFragment) {
return input.endsWith("/");
}
return TRAILING_SLASH_RE.test(input);
}
function withoutTrailingSlash(input = "", respectQueryAndFragment) {
if (!respectQueryAndFragment) {
return (hasTrailingSlash(input) ? input.slice(0, -1) : input) || "/";
}
if (!hasTrailingSlash(input, true)) {
return input || "/";
}
let path = input;
let fragment = "";
const fragmentIndex = input.indexOf("#");
if (fragmentIndex !== -1) {
path = input.slice(0, fragmentIndex);
fragment = input.slice(fragmentIndex);
}
const [s0, ...s] = path.split("?");
const cleanPath = s0.endsWith("/") ? s0.slice(0, -1) : s0;
return (cleanPath || "/") + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
}
function withTrailingSlash(input = "", respectQueryAndFragment) {
if (!respectQueryAndFragment) {
return input.endsWith("/") ? input : input + "/";
}
if (hasTrailingSlash(input, true)) {
return input || "/";
}
let path = input;
let fragment = "";
const fragmentIndex = input.indexOf("#");
if (fragmentIndex !== -1) {
path = input.slice(0, fragmentIndex);
fragment = input.slice(fragmentIndex);
if (!path) {
return fragment;
}
}
const [s0, ...s] = path.split("?");
return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
}
function hasLeadingSlash(input = "") {
return input.startsWith("/");
}
function withLeadingSlash(input = "") {
return hasLeadingSlash(input) ? input : "/" + input;
}
function withBase(input, base) {
if (isEmptyURL(base) || hasProtocol(input)) {
return input;
}
const _base = withoutTrailingSlash(base);
if (input.startsWith(_base)) {
const nextChar = input[_base.length];
if (!nextChar || nextChar === "/" || nextChar === "?") {
return input;
}
}
return joinURL(_base, input);
}
function withoutBase(input, base) {
if (isEmptyURL(base)) {
return input;
}
const _base = withoutTrailingSlash(base);
if (!input.startsWith(_base)) {
return input;
}
const nextChar = input[_base.length];
if (nextChar && nextChar !== "/" && nextChar !== "?") {
return input;
}
const trimmed = input.slice(_base.length).replace(/^\/+/, "");
return "/" + trimmed;
}
function withQuery(input, query) {
const parsed = parseURL(input);
const mergedQuery = { ...parseQuery(parsed.search), ...query };
parsed.search = stringifyQuery(mergedQuery);
return stringifyParsedURL(parsed);
}
function getQuery$1(input) {
return parseQuery(parseURL(input).search);
}
function isEmptyURL(url) {
return !url || url === "/";
}
function isNonEmptyURL(url) {
return url && url !== "/";
}
function joinURL(base, ...input) {
let url = base || "";
for (const segment of input.filter((url2) => isNonEmptyURL(url2))) {
if (url) {
const _segment = segment.replace(JOIN_LEADING_SLASH_RE, "");
url = withTrailingSlash(url) + _segment;
} else {
url = segment;
}
}
return url;
}
function joinRelativeURL(..._input) {
const JOIN_SEGMENT_SPLIT_RE = /\/(?!\/)/;
const input = _input.filter(Boolean);
const segments = [];
let segmentsDepth = 0;
for (const i of input) {
if (!i || i === "/") {
continue;
}
for (const [sindex, s] of i.split(JOIN_SEGMENT_SPLIT_RE).entries()) {
if (!s || s === ".") {
continue;
}
if (s === "..") {
if (segments.length === 1 && hasProtocol(segments[0])) {
continue;
}
segments.pop();
segmentsDepth--;
continue;
}
if (sindex === 1 && segments[segments.length - 1]?.endsWith(":/")) {
segments[segments.length - 1] += "/" + s;
continue;
}
segments.push(s);
segmentsDepth++;
}
}
let url = segments.join("/");
if (segmentsDepth >= 0) {
if (input[0]?.startsWith("/") && !url.startsWith("/")) {
url = "/" + url;
} else if (input[0]?.startsWith("./") && !url.startsWith("./")) {
url = "./" + url;
}
} else {
url = "../".repeat(-1 * segmentsDepth) + url;
}
if (input[input.length - 1]?.endsWith("/") && !url.endsWith("/")) {
url += "/";
}
return url;
}
const protocolRelative = Symbol.for("ufo:protocolRelative");
function parseURL(input = "", defaultProto) {
const _specialProtoMatch = input.match(
/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i
);
if (_specialProtoMatch) {
const [, _proto, _pathname = ""] = _specialProtoMatch;
return {
protocol: _proto.toLowerCase(),
pathname: _pathname,
href: _proto + _pathname,
auth: "",
host: "",
search: "",
hash: ""
};
}
if (!hasProtocol(input, { acceptRelative: true })) {
return parsePath(input);
}
const [, protocol = "", auth, hostAndPath = ""] = input.replace(/\\/g, "/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/) || [];
let [, host = "", path = ""] = hostAndPath.match(/([^#/?]*)(.*)?/) || [];
if (protocol === "file:") {
path = path.replace(/\/(?=[A-Za-z]:)/, "");
}
const { pathname, search, hash } = parsePath(path);
return {
protocol: protocol.toLowerCase(),
auth: auth ? auth.slice(0, Math.max(0, auth.length - 1)) : "",
host,
pathname,
search,
hash,
[protocolRelative]: !protocol
};
}
function parsePath(input = "") {
const [pathname = "", search = "", hash = ""] = (input.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1);
return {
pathname,
search,
hash
};
}
function stringifyParsedURL(parsed) {
const pathname = parsed.pathname || "";
const search = parsed.search ? (parsed.search.startsWith("?") ? "" : "?") + parsed.search : "";
const hash = parsed.hash || "";
const auth = parsed.auth ? parsed.auth + "@" : "";
const host = parsed.host || "";
const proto = parsed.protocol || parsed[protocolRelative] ? (parsed.protocol || "") + "//" : "";
return proto + auth + host + pathname + search + hash;
}
const NullObject$1 = /* @__PURE__ */ (() => {
const C = function() {
};
C.prototype = /* @__PURE__ */ Object.create(null);
return C;
})();
function parse$1(str, options) {
if (typeof str !== "string") {
throw new TypeError("argument str must be a string");
}
const obj = new NullObject$1();
const opt = {};
const dec = opt.decode || decode$1;
let index = 0;
while (index < str.length) {
const eqIdx = str.indexOf("=", index);
if (eqIdx === -1) {
break;
}
let endIdx = str.indexOf(";", index);
if (endIdx === -1) {
endIdx = str.length;
} else if (endIdx < eqIdx) {
index = str.lastIndexOf(";", eqIdx - 1) + 1;
continue;
}
const key = str.slice(index, eqIdx).trim();
if (opt?.filter && !opt?.filter(key)) {
index = endIdx + 1;
continue;
}
if (void 0 === obj[key]) {
let val = str.slice(eqIdx + 1, endIdx).trim();
if (val.codePointAt(0) === 34) {
val = val.slice(1, -1);
}
obj[key] = tryDecode$1(val, dec);
}
index = endIdx + 1;
}
return obj;
}
function decode$1(str) {
return str.includes("%") ? decodeURIComponent(str) : str;
}
function tryDecode$1(str, decode2) {
try {
return decode2(str);
} catch {
return str;
}
}
const fieldContentRegExp = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/;
function serialize$2(name, value, options) {
const opt = options || {};
const enc = opt.encode || encodeURIComponent;
if (typeof enc !== "function") {
throw new TypeError("option encode is invalid");
}
if (!fieldContentRegExp.test(name)) {
throw new TypeError("argument name is invalid");
}
const encodedValue = enc(value);
if (encodedValue && !fieldContentRegExp.test(encodedValue)) {
throw new TypeError("argument val is invalid");
}
let str = name + "=" + encodedValue;
if (void 0 !== opt.maxAge && opt.maxAge !== null) {
const maxAge = opt.maxAge - 0;
if (Number.isNaN(maxAge) || !Number.isFinite(maxAge)) {
throw new TypeError("option maxAge is invalid");
}
str += "; Max-Age=" + Math.floor(maxAge);
}
if (opt.domain) {
if (!fieldContentRegExp.test(opt.domain)) {
throw new TypeError("option domain is invalid");
}
str += "; Domain=" + opt.domain;
}
if (opt.path) {
if (!fieldContentRegExp.test(opt.path)) {
throw new TypeError("option path is invalid");
}
str += "; Path=" + opt.path;
}
if (opt.expires) {
if (!isDate(opt.expires) || Number.isNaN(opt.expires.valueOf())) {
throw new TypeError("option expires is invalid");
}
str += "; Expires=" + opt.expires.toUTCString();
}
if (opt.httpOnly) {
str += "; HttpOnly";
}
if (opt.secure) {
str += "; Secure";
}
if (opt.priority) {
const priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority;
switch (priority) {
case "low": {
str += "; Priority=Low";
break;
}
case "medium": {
str += "; Priority=Medium";
break;
}
case "high": {
str += "; Priority=High";
break;
}
default: {
throw new TypeError("option priority is invalid");
}
}
}
if (opt.sameSite) {
const sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
switch (sameSite) {
case true: {
str += "; SameSite=Strict";
break;
}
case "lax": {
str += "; SameSite=Lax";
break;
}
case "strict": {
str += "; SameSite=Strict";
break;
}
case "none": {
str += "; SameSite=None";
break;
}
default: {
throw new TypeError("option sameSite is invalid");
}
}
}
if (opt.partitioned) {
str += "; Partitioned";
}
return str;
}
function isDate(val) {
return Object.prototype.toString.call(val) === "[object Date]" || val instanceof Date;
}
function parseSetCookie(setCookieValue, options) {
const parts = (setCookieValue || "").split(";").filter((str) => typeof str === "string" && !!str.trim());
const nameValuePairStr = parts.shift() || "";
const parsed = _parseNameValuePair(nameValuePairStr);
const name = parsed.name;
let value = parsed.value;
try {
value = options?.decode === false ? value : (options?.decode || decodeURIComponent)(value);
} catch {
}
const cookie = {
name,
value
};
for (const part of parts) {
const sides = part.split("=");
const partKey = (sides.shift() || "").trimStart().toLowerCase();
const partValue = sides.join("=");
switch (partKey) {
case "expires": {
cookie.expires = new Date(partValue);
break;
}
case "max-age": {
cookie.maxAge = Number.parseInt(partValue, 10);
break;
}
case "secure": {
cookie.secure = true;
break;
}
case "httponly": {
cookie.httpOnly = true;
break;
}
case "samesite": {
cookie.sameSite = partValue;
break;
}
default: {
cookie[partKey] = partValue;
}
}
}
return cookie;
}
function _parseNameValuePair(nameValuePairStr) {
let name = "";
let value = "";
const nameValueArr = nameValuePairStr.split("=");
if (nameValueArr.length > 1) {
name = nameValueArr.shift();
value = nameValueArr.join("=");
} else {
value = nameValuePairStr;
}
return { name, value };
}
const NODE_TYPES = {
NORMAL: 0,
WILDCARD: 1,
PLACEHOLDER: 2
};
function createRouter$1(options = {}) {
const ctx = {
options,
rootNode: createRadixNode(),
staticRoutesMap: {}
};
const normalizeTrailingSlash = (p) => options.strictTrailingSlash ? p : p.replace(/\/$/, "") || "/";
if (options.routes) {
for (const path in options.routes) {
insert(ctx, normalizeTrailingSlash(path), options.routes[path]);
}
}
return {
ctx,
lookup: (path) => lookup(ctx, normalizeTrailingSlash(path)),
insert: (path, data) => insert(ctx, normalizeTrailingSlash(path), data),
remove: (path) => remove(ctx, normalizeTrailingSlash(path))
};
}
function lookup(ctx, path) {
const staticPathNode = ctx.staticRoutesMap[path];
if (staticPathNode) {
return staticPathNode.data;
}
const sections = path.split("/");
const params = {};
let paramsFound = false;
let wildcardNode = null;
let node = ctx.rootNode;
let wildCardParam = null;
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
if (node.wildcardChildNode !== null) {
wildcardNode = node.wildcardChildNode;
wildCardParam = sections.slice(i).join("/");
}
const nextNode = node.children.get(section);
if (nextNode === void 0) {
if (node && node.placeholderChildren.length > 1) {
const remaining = sections.length - i;
node = node.placeholderChildren.find((c) => c.maxDepth === remaining) || null;
} else {
node = node.placeholderChildren[0] || null;
}
if (!node) {
break;
}
if (node.paramName) {
params[node.paramName] = section;
}
paramsFound = true;
} else {
node = nextNode;
}
}
if ((node === null || node.data === null) && wildcardNode !== null) {
node = wildcardNode;
params[node.paramName || "_"] = wildCardParam;
paramsFound = true;
}
if (!node) {
return null;
}
if (paramsFound) {
return {
...node.data,
params: paramsFound ? params : void 0
};
}
return node.data;
}
function insert(ctx, path, data) {
let isStaticRoute = true;
const sections = path.split("/");
let node = ctx.rootNode;
let _unnamedPlaceholderCtr = 0;
const matchedNodes = [node];
for (const section of sections) {
let childNode;
if (childNode = node.children.get(section)) {
node = childNode;
} else {
const type = getNodeType(section);
childNode = createRadixNode({ type, parent: node });
node.children.set(section, childNode);
if (type === NODE_TYPES.PLACEHOLDER) {
childNode.paramName = section === "*" ? `_${_unnamedPlaceholderCtr++}` : section.slice(1);
node.placeholderChildren.push(childNode);
isStaticRoute = false;
} else if (type === NODE_TYPES.WILDCARD) {
node.wildcardChildNode = childNode;
childNode.paramName = section.slice(
3
/* "**:" */
) || "_";
isStaticRoute = false;
}
matchedNodes.push(childNode);
node = childNode;
}
}
for (const [depth, node2] of matchedNodes.entries()) {
node2.maxDepth = Math.max(matchedNodes.length - depth, node2.maxDepth || 0);
}
node.data = data;
if (isStaticRoute === true) {
ctx.staticRoutesMap[path] = node;
}
return node;
}
function remove(ctx, path) {
let success = false;
const sections = path.split("/");
let node = ctx.rootNode;
for (const section of sections) {
node = node.children.get(section);
if (!node) {
return success;
}
}
if (node.data) {
const lastSection = sections.at(-1) || "";
node.data = null;
if (Object.keys(node.children).length === 0 && node.parent) {
node.parent.children.delete(lastSection);
node.parent.wildcardChildNode = null;
node.parent.placeholderChildren = [];
}
success = true;
}
return success;
}
function createRadixNode(options = {}) {
return {
type: options.type || NODE_TYPES.NORMAL,
maxDepth: 0,
parent: options.parent || null,
children: /* @__PURE__ */ new Map(),
data: options.data || null,
paramName: options.paramName || null,
wildcardChildNode: null,
placeholderChildren: []
};
}
function getNodeType(str) {
if (str.startsWith("**")) {
return NODE_TYPES.WILDCARD;
}
if (str[0] === ":" || str === "*") {
return NODE_TYPES.PLACEHOLDER;
}
return NODE_TYPES.NORMAL;
}
function toRouteMatcher(router) {
const table = _routerNodeToTable("", router.ctx.rootNode);
return _createMatcher(table, router.ctx.options.strictTrailingSlash);
}
function _createMatcher(table, strictTrailingSlash) {
return {
ctx: { table },
matchAll: (path) => _matchRoutes(path, table, strictTrailingSlash)
};
}
function _createRouteTable() {
return {
static: /* @__PURE__ */ new Map(),
wildcard: /* @__PURE__ */ new Map(),
dynamic: /* @__PURE__ */ new Map()
};
}
function _matchRoutes(path, table, strictTrailingSlash) {
if (strictTrailingSlash !== true && path.endsWith("/")) {
path = path.slice(0, -1) || "/";
}
const matches = [];
for (const [key, value] of _sortRoutesMap(table.wildcard)) {
if (path === key || path.startsWith(key + "/")) {
matches.push(value);
}
}
for (const [key, value] of _sortRoutesMap(table.dynamic)) {
if (path.startsWith(key + "/")) {
const subPath = "/" + path.slice(key.length).split("/").splice(2).join("/");
matches.push(..._matchRoutes(subPath, value));
}
}
const staticMatch = table.static.get(path);
if (staticMatch) {
matches.push(staticMatch);
}
return matches.filter(Boolean);
}
function _sortRoutesMap(m) {
return [...m.entries()].sort((a, b) => a[0].length - b[0].length);
}
function _routerNodeToTable(initialPath, initialNode) {
const table = _createRouteTable();
function _addNode(path, node) {
if (path) {
if (node.type === NODE_TYPES.NORMAL && !(path.includes("*") || path.includes(":"))) {
if (node.data) {
table.static.set(path, node.data);
}
} else if (node.type === NODE_TYPES.WILDCARD) {
table.wildcard.set(path.replace("/**", ""), node.data);
} else if (node.type === NODE_TYPES.PLACEHOLDER) {
const subTable = _routerNodeToTable("", node);
if (node.data) {
subTable.static.set("/", node.data);
}
table.dynamic.set(path.replace(/\/\*|\/:\w+/, ""), subTable);
return;
}
}
for (const [childPath, child] of node.children.entries()) {
_addNode(`${path}/${childPath}`.replace("//", "/"), child);
}
}
_addNode(initialPath, initialNode);
return table;
}
function isPlainObject(value) {
if (value === null || typeof value !== "object") {
return false;
}
const prototype = Object.getPrototypeOf(value);
if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
return false;
}
if (Symbol.iterator in value) {
return false;
}
if (Symbol.toStringTag in value) {
return Object.prototype.toString.call(value) === "[object Module]";
}
return true;
}
function _defu(baseObject, defaults, namespace = ".", merger) {
if (!isPlainObject(defaults)) {
return _defu(baseObject, {}, namespace, merger);
}
const object = { ...defaults };
for (const key of Object.keys(baseObject)) {
if (key === "__proto__" || key === "constructor") {
continue;
}
const value = baseObject[key];
if (value === null || value === void 0) {
continue;
}
if (merger && merger(object, key, value, namespace)) {
continue;
}
if (Array.isArray(value) && Array.isArray(object[key])) {
object[key] = [...value, ...object[key]];
} else if (isPlainObject(value) && isPlainObject(object[key])) {
object[key] = _defu(
value,
object[key],
(namespace ? `${namespace}.` : "") + key.toString(),
merger
);
} else {
object[key] = value;
}
}
return object;
}
function createDefu(merger) {
return (...arguments_) => (
// eslint-disable-next-line unicorn/no-array-reduce
arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
);
}
const defu = createDefu();
const defuFn = createDefu((object, key, currentValue) => {
if (object[key] !== void 0 && typeof currentValue === "function") {
object[key] = currentValue(object[key]);
return true;
}
});
function o(n){throw new Error(`${n} is not implemented yet!`)}let i$1 = class i extends EventEmitter{__unenv__={};readableEncoding=null;readableEnded=true;readableFlowing=false;readableHighWaterMark=0;readableLength=0;readableObjectMode=false;readableAborted=false;readableDidRead=false;closed=false;errored=null;readable=false;destroyed=false;static from(e,t){return new i(t)}constructor(e){super();}_read(e){}read(e){}setEncoding(e){return this}pause(){return this}resume(){return this}isPaused(){return true}unpipe(e){return this}unshift(e,t){}wrap(e){return this}push(e,t){return false}_destroy(e,t){this.removeAllListeners();}destroy(e){return this.destroyed=true,this._destroy(e),this}pipe(e,t){return {}}compose(e,t){throw new Error("Method not implemented.")}[Symbol.asyncDispose](){return this.destroy(),Promise.resolve()}async*[Symbol.asyncIterator](){throw o("Readable.asyncIterator")}iterator(e){throw o("Readable.iterator")}map(e,t){throw o("Readable.map")}filter(e,t){throw o("Readable.filter")}forEach(e,t){throw o("Readable.forEach")}reduce(e,t,r){throw o("Readable.reduce")}find(e,t){throw o("Readable.find")}findIndex(e,t){throw o("Readable.findIndex")}some(e,t){throw o("Readable.some")}toArray(e){throw o("Readable.toArray")}every(e,t){throw o("Readable.every")}flatMap(e,t){throw o("Readable.flatMap")}drop(e,t){throw o("Readable.drop")}take(e,t){throw o("Readable.take")}asIndexedPairs(e){throw o("Readable.asIndexedPairs")}};let l$1 = class l extends EventEmitter{__unenv__={};writable=true;writableEnded=false;writableFinished=false;writableHighWaterMark=0;writableLength=0;writableObjectMode=false;writableCorked=0;closed=false;errored=null;writableNeedDrain=false;writableAborted=false;destroyed=false;_data;_encoding="utf8";constructor(e){super();}pipe(e,t){return {}}_write(e,t,r){if(this.writableEnded){r&&r();return}if(this._data===void 0)this._data=e;else {const s=typeof this._data=="string"?Buffer$1.from(this._data,this._encoding||t||"utf8"):this._data,a=typeof e=="string"?Buffer$1.from(e,t||this._encoding||"utf8"):e;this._data=Buffer$1.concat([s,a]);}this._encoding=t,r&&r();}_writev(e,t){}_destroy(e,t){}_final(e){}write(e,t,r){const s=typeof t=="string"?this._encoding:"utf8",a=typeof t=="function"?t:typeof r=="function"?r:void 0;return this._write(e,s,a),true}setDefaultEncoding(e){return this}end(e,t,r){const s=typeof e=="function"?e:typeof t=="function"?t:typeof r=="function"?r:void 0;if(this.writableEnded)return s&&s(),this;const a=e===s?void 0:e;if(a){const u=t===s?void 0:t;this.write(a,u,s);}return this.writableEnded=true,this.writableFinished=true,this.emit("close"),this.emit("finish"),this}cork(){}uncork(){}destroy(e){return this.destroyed=true,delete this._data,this.removeAllListeners(),this}compose(e,t){throw new Error("Method not implemented.")}[Symbol.asyncDispose](){return Promise.resolve()}};const c$1=class c{allowHalfOpen=true;_destroy;constructor(e=new i$1,t=new l$1){Object.assign(this,e),Object.assign(this,t),this._destroy=m(e._destroy,t._destroy);}};function _(){return Object.assign(c$1.prototype,i$1.prototype),Object.assign(c$1.prototype,l$1.prototype),c$1}function m(...n){return function(...e){for(const t of n)t(...e);}}const g=_();class A extends g{__unenv__={};bufferSize=0;bytesRead=0;bytesWritten=0;connecting=false;destroyed=false;pending=false;localAddress="";localPort=0;remoteAddress="";remoteFamily="";remotePort=0;autoSelectFamilyAttemptedAddresses=[];readyState="readOnly";constructor(e){super();}write(e,t,r){return false}connect(e,t,r){return this}end(e,t,r){return this}setEncoding(e){return this}pause(){return this}resume(){return this}setTimeout(e,t){return this}setNoDelay(e){return this}setKeepAlive(e,t){return this}address(){return {}}unref(){return this}ref(){return this}destroySoon(){this.destroy();}resetAndDestroy(){const e=new Error("ERR_SOCKET_CLOSED");return e.code="ERR_SOCKET_CLOSED",this.destroy(e),this}}class y extends i$1{aborted=false;httpVersion="1.1";httpVersionMajor=1;httpVersionMinor=1;complete=true;connection;socket;headers={};trailers={};method="GET";url="/";statusCode=200;statusMessage="";closed=false;errored=null;readable=false;constructor(e){super(),this.socket=this.connection=e||new A;}get rawHeaders(){const e=this.headers,t=[];for(const r in e)if(Array.isArray(e[r]))for(const s of e[r])t.push(r,s);else t.push(r,e[r]);return t}get rawTrailers(){return []}setTimeout(e,t){return this}get headersDistinct(){return p(this.headers)}get trailersDistinct(){return p(this.trailers)}}function p(n){const e={};for(const[t,r]of Object.entries(n))t&&(e[t]=(Array.isArray(r)?r:[r]).filter(Boolean));return e}class w extends l$1{statusCode=200;statusMessage="";upgrading=false;chunkedEncoding=false;shouldKeepAlive=false;useChunkedEncodingByDefault=false;sendDate=false;finished=false;headersSent=false;strictContentLength=false;connection=null;socket=null;req;_headers={};constructor(e){super(),this.req=e;}assignSocket(e){e._httpMessage=this,this.socket=e,this.connection=e,this.emit("socket",e),this._flush();}_flush(){this.flushHeaders();}detachSocket(e){}writeContinue(e){}writeHead(e,t,r){e&&(this.statusCode=e),typeof t=="string"&&(this.statusMessage=t,t=void 0);const s=r||t;if(s&&!Array.isArray(s))for(const a in s)this.setHeader(a,s[a]);return this.headersSent=true,this}writeProcessing(){}setTimeout(e,t){return this}appendHeader(e,t){e=e.toLowerCase();const r=this._headers[e],s=[...Array.isArray(r)?r:[r],...Array.isArray(t)?t:[t]].filter(Boolean);return this._headers[e]=s.length>1?s:s[0],this}setHeader(e,t){return this._headers[e.toLowerCase()]=t,this}setHeaders(e){for(const[t,r]of Object.entries(e))this.setHeader(t,r);return this}getHeader(e){return this._headers[e.toLowerCase()]}getHeaders(){return this._headers}getHeaderNames(){return Object.keys(this._headers)}hasHeader(e){return e.toLowerCase()in this._headers}removeHeader(e){delete this._headers[e.toLowerCase()];}addTrailers(e){}flushHeaders(){}writeEarlyHints(e,t){typeof t=="function"&&t();}}const E=(()=>{const n=function(){};return n.prototype=Object.create(null),n})();function R(n={}){const e=new E,t=Array.isArray(n)||H(n)?n:Object.entries(n);for(const[r,s]of t)if(s){if(e[r]===void 0){e[r]=s;continue}e[r]=[...Array.isArray(e[r])?e[r]:[e[r]],...Array.isArray(s)?s:[s]];}return e}function H(n){return typeof n?.entries=="function"}function v(n={}){if(n instanceof Headers)return n;const e=new Headers;for(const[t,r]of Object.entries(n))if(r!==void 0){if(Array.isArray(r)){for(const s of r)e.append(t,String(s));continue}e.set(t,String(r));}return e}const S=new Set([101,204,205,304]);async function b(n,e){const t=new y,r=new w(t);t.url=e.url?.toString()||"/";let s;if(!t.url.startsWith("/")){const d=new URL(t.url);s=d.host,t.url=d.pathname+d.search+d.hash;}t.method=e.method||"GET",t.headers=R(e.headers||{}),t.headers.host||(t.headers.host=e.host||s||"localhost"),t.connection.encrypted=t.connection.encrypted||e.protocol==="https",t.body=e.body||null,t.__unenv__=e.context,await n(t,r);let a=r._data;(S.has(r.statusCode)||t.method.toUpperCase()==="HEAD")&&(a=null,delete r._headers["content-length"]);const u={status:r.statusCode,statusText:r.statusMessage,headers:r._headers,body:a};return t.destroy(),r.destroy(),u}async function C(n,e,t={}){try{const r=await b(n,{url:e,...t});return new Response(r.body,{status:r.status,statusText:r.statusText,headers:v(r.headers)})}catch(r){return new Response(r.toString(),{status:Number.parseInt(r.statusCode||r.code)||500,statusText:r.statusText})}}
function hasProp(obj, prop) {
try {
return prop in obj;
} catch {
return false;
}
}
class H3Error extends Error {
static __h3_error__ = true;
statusCode = 500;
fatal = false;
unhandled = false;
statusMessage;
data;
cause;
constructor(message, opts = {}) {
super(message, opts);
if (opts.cause && !this.cause) {
this.cause = opts.cause;
}
}
toJSON() {
const obj = {
message: this.message,
statusCode: sanitizeStatusCode(this.statusCode, 500)
};
if (this.statusMessage) {
obj.statusMessage = sanitizeStatusMessage(this.statusMessage);
}
if (this.data !== void 0) {
obj.data = this.data;
}
return obj;
}
}
function createError$1(input) {
if (typeof input === "string") {
return new H3Error(input);
}
if (isError(input)) {
return input;
}
const err = new H3Error(input.message ?? input.statusMessage ?? "", {
cause: input.cause || input
});
if (hasProp(input, "stack")) {
try {
Object.defineProperty(err, "stack", {
get() {
return input.stack;
}
});
} catch {
try {
err.stack = input.stack;
} catch {
}
}
}
if (input.data) {
err.data = input.data;
}
if (input.statusCode) {
err.statusCode = sanitizeStatusCode(input.statusCode, err.statusCode);
} else if (input.status) {
err.statusCode = sanitizeStatusCode(input.status, err.statusCode);
}
if (input.statusMessage) {
err.statusMessage = input.statusMessage;
} else if (input.statusText) {
err.statusMessage = input.statusText;
}
if (err.statusMessage) {
const originalMessage = err.statusMessage;
const sanitizedMessage = sanitizeStatusMessage(err.statusMessage);
if (sanitizedMessage !== originalMessage) {
console.warn(
"[h3] Please prefer using `message` for longer error messages instead of `statusMessage`. In the future, `statusMessage` will be sanitized by default."
);
}
}
if (input.fatal !== void 0) {
err.fatal = input.fatal;
}
if (input.unhandled !== void 0) {
err.unhandled = input.unhandled;
}
return err;
}
function sendError(event, error, debug) {
if (event.handled) {
return;
}
const h3Error = isError(error) ? error : createError$1(error);
const responseBody = {
statusCode: h3Error.statusCode,
statusMessage: h3Error.statusMessage,
stack: [],
data: h3Error.data
};
if (debug) {
responseBody.stack = (h3Error.stack || "").split("\n").map((l) => l.trim());
}
if (event.handled) {
return;
}
const _code = Number.parseInt(h3Error.statusCode);
setResponseStatus(event, _code, h3Error.statusMessage);
event.node.res.setHeader("content-type", MIMES.json);
event.node.res.end(JSON.stringify(responseBody, void 0, 2));
}
function isError(input) {
return input?.constructor?.__h3_error__ === true;
}
function getQuery(event) {
return getQuery$1(event.path || "");
}
function getRouterParams(event, opts = {}) {
let params = event.context.params || {};
if (opts.decode) {
params = { ...params };
for (const key in params) {
params[key] = decode$2(params[key]);
}
}
return params;
}
function getRouterParam(event, name, opts = {}) {
const params = getRouterParams(event, opts);
return params[name];
}
function isMethod(event, expected, allowHead) {
if (typeof expected === "string") {
if (event.method === expected) {
return true;
}
} else if (expected.includes(event.method)) {
return true;
}
return false;
}
function assertMethod(event, expected, allowHead) {
if (!isMethod(event, expected)) {
throw createError$1({
statusCode: 405,
statusMessage: "HTTP method is not allowed."
});
}
}
function getRequestHeaders(event) {
const _headers = {};
for (const key in event.node.req.headers) {
const val = event.node.req.headers[key];
_headers[key] = Array.isArray(val) ? val.filter(Boolean).join(", ") : val;
}
return _headers;
}
function getRequestHeader(event, name) {
const headers = getRequestHeaders(event);
const value = headers[name.toLowerCase()];
return value;
}
function getRequestHost(event, opts = {}) {
if (opts.xForwardedHost) {
const _header = event.node.req.headers["x-forwarded-host"];
const xForwardedHost = (_header || "").split(",").shift()?.trim();
if (xForwardedHost) {
return xForwardedHost;
}
}
return event.node.req.headers.host || "localhost";
}
function getRequestProtocol(event, opts = {}) {
if (opts.xForwardedProto !== false && event.node.req.headers["x-forwarded-proto"] === "https") {
return "https";
}
return event.node.req.connection?.encrypted ? "https" : "http";
}
function getRequestURL(event, opts = {}) {
const host = getRequestHost(event, opts);
const protocol = getRequestProtocol(event, opts);
const path = (event.node.req.originalUrl || event.path).replace(
/^[/\\]+/g,
"/"
);
return new URL(path, `${protocol}://${host}`);
}
const RawBodySymbol = Symbol.for("h3RawBody");
const PayloadMethods$1 = ["PATCH", "POST", "PUT", "DELETE"];
function readRawBody(event, encoding = "utf8") {
assertMethod(event, PayloadMethods$1);
const _rawBody = event._requestBody || event.web?.request?.body || event.node.req[RawBodySymbol] || event.node.req.rawBody || event.node.req.body;
if (_rawBody) {
const promise2 = Promise.resolve(_rawBody).then((_resolved) => {
if (Buffer.isBuffer(_resolved)) {
return _resolved;
}
if (typeof _resolved.pipeTo === "function") {
return new Promise((resolve, reject) => {
const chunks = [];
_resolved.pipeTo(
new WritableStream({
write(chunk) {
chunks.push(chunk);
},
close() {
resolve(Buffer.concat(chunks));
},
abort(reason) {
reject(reason);
}
})
).catch(reject);
});
} else if (typeof _resolved.pipe === "function") {
return new Promise((resolve, reject) => {
const chunks = [];
_resolved.on("data", (chunk) => {
chunks.push(chunk);
}).on("end", () => {
resolve(Buffer.concat(chunks));
}).on("error", reject);
});
}
if (_resolved.constructor === Object) {
return Buffer.from(JSON.stringify(_resolved));
}
if (_resolved instanceof URLSearchParams) {
return Buffer.from(_resolved.toString());
}
if (_resolved instanceof FormData) {
return new Response(_resolved).bytes().then((uint8arr) => Buffer.from(uint8arr));
}
return Buffer.from(_resolved);
});
return encoding ? promise2.then((buff) => buff.toString(encoding)) : promise2;
}
if (!Number.parseInt(event.node.req.headers["content-length"] || "") && !/\bchunked\b/i.test(
String(event.node.req.headers["transfer-encoding"] ?? "")
)) {
return Promise.resolve(void 0);
}
const promise = event.node.req[RawBodySymbol] = new Promise(
(resolve, reject) => {
const bodyData = [];
event.node.req.on("error", (err) => {
reject(err);
}).on("data", (chunk) => {
bodyData.push(chunk);
}).on("end", () => {
resolve(Buffer.concat(bodyData));
});
}
);
const result = encoding ? promise.then((buff) => buff.toString(encoding)) : promise;
return result;
}
function getRequestWebStream(event) {
if (!PayloadMethods$1.includes(event.method)) {
return;
}
const bodyStream = event.web?.request?.body || event._requestBody;
if (bodyStream) {
return bodyStream;
}
const _hasRawBody = RawBodySymbol in event.node.req || "rawBody" in event.node.req || "body" in event.node.req || "__unenv__" in event.node.req;
if (_hasRawBody) {
return new ReadableStream({
async start(controller) {
const _rawBody = await readRawBody(event, false);
if (_rawBody) {
controller.enqueue(_rawBody);
}
controller.close();
}
});
}
return new ReadableStream({
start: (controller) => {
event.node.req.on("data", (chunk) => {
controller.enqueue(chunk);
});
event.node.req.on("end", () => {
controller.close();
});
event.node.req.on("error", (err) => {
controller.error(err);
});
}
});
}
function handleCacheHeaders(event, opts) {
const cacheControls = ["public", ...opts.cacheControls || []];
let cacheMatched = false;
if (opts.maxAge !== void 0) {
cacheControls.push(`max-age=${+opts.maxAge}`, `s-maxage=${+opts.maxAge}`);
}
if (opts.modifiedTime) {
const modifiedTime = new Date(opts.modifiedTime);
const ifModifiedSince = event.node.req.headers["if-modified-since"];
event.node.res.setHeader("last-modified", modifiedTime.toUTCString());
if (ifModifiedSince && new Date(ifModifiedSince) >= modifiedTime) {
cacheMatched = true;
}
}
if (opts.etag) {
event.node.res.setHeader("etag", opts.etag);
const ifNonMatch = event.node.req.headers["if-none-match"];
if (ifNonMatch === opts.etag) {
cacheMatched = true;
}
}
event.node.res.setHeader("cache-control", cacheControls.join(", "));
if (cacheMatched) {
event.node.res.statusCode = 304;
if (!event.handled) {
event.node.res.end();
}
return true;
}
return false;
}
const MIMES = {
html: "text/html",
json: "application/json"
};
const DISALLOWED_STATUS_CHARS = /[^\u0009\u0020-\u007E]/g;
function sanitizeStatusMessage(statusMessage = "") {
return statusMessage.replace(DISALLOWED_STATUS_CHARS, "");
}
function sanitizeStatusCode(statusCode, defaultStatusCode = 200) {
if (!statusCode) {
return defaultStatusCode;
}
if (typeof statusCode === "string") {
statusCode = Number.parseInt(statusCode, 10);
}
if (statusCode < 100 || statusCode > 999) {
return defaultStatusCode;
}
return statusCode;
}
function getDistinctCookieKey(name, opts) {
return [name, opts.domain || "", opts.path || "/"].join(";");
}
function parseCookies(event) {
return parse$1(event.node.req.headers.cookie || "");
}
function getCookie(event, name) {
return parseCookies(event)[name];
}
function setCookie(event, name, value, serializeOptions = {}) {
if (!serializeOptions.path) {
serializeOptions = { path: "/", ...serializeOptions };
}
const newCookie = serialize$2(name, value, serializeOptions);
const currentCookies = splitCookiesString(
event.node.res.getHeader("set-cookie")
);
if (currentCookies.length === 0) {
event.node.res.setHeader("set-cookie", newCookie);
return;
}
const newCookieKey = getDistinctCookieKey(name, serializeOptions);
event.node.res.removeHeader("set-cookie");
for (const cookie of currentCookies) {
const parsed = parseSetCookie(cookie);
const key = getDistinctCookieKey(parsed.name, parsed);
if (key === newCookieKey) {
continue;
}
event.node.res.appendHeader("set-cookie", cookie);
}
event.node.res.appendHeader("set-cookie", newCookie);
}
function deleteCookie(event, name, serializeOptions) {
setCookie(event, name, "", {
...serializeOptions,
maxAge: 0
});
}
function splitCookiesString(cookiesString) {
if (Array.isArray(cookiesString)) {
return cookiesString.flatMap((c) => splitCookiesString(c));
}
if (typeof cookiesString !== "string") {
return [];
}
const cookiesStrings = [];
let pos = 0;
let start;
let ch;
let lastComma;
let nextStart;
let cookiesSeparatorFound;
const skipWhitespace = () => {
while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
pos += 1;
}
return pos < cookiesString.length;
};
const notSpecialChar = () => {
ch = cookiesString.charAt(pos);
return ch !== "=" && ch !== ";" && ch !== ",";
};
while (pos < cookiesString.length) {
start = pos;
cookiesSeparatorFound = false;
while (skipWhitespace()) {
ch = cookiesString.charAt(pos);
if (ch === ",") {
lastComma = pos;
pos += 1;
skipWhitespace();
nextStart = pos;
while (pos < cookiesString.length && notSpecialChar()) {
pos += 1;
}
if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
cookiesSeparatorFound = true;
pos = nextStart;
cookiesStrings.push(cookiesString.slice(start, lastComma));
start = pos;
} else {
pos = lastComma + 1;
}
} else {
pos += 1;
}
}
if (!cookiesSeparatorFound || pos >= cookiesString.length) {
cookiesStrings.push(cookiesString.slice(start));
}
}
return cookiesStrings;
}
const defer = typeof setImmediate === "undefined" ? (fn) => fn() : setImmediate;
function send(event, data, type) {
if (type) {
defaultContentType(event, type);
}
return new Promise((resolve) => {
defer(() => {
if (!event.handled) {
event.node.res.end(data);
}
resolve();
});
});
}
function sendNoContent(event, code) {
if (event.handled) {
return;
}
if (!code && event.node.res.statusCode !== 200) {
code = event.node.res.statusCode;
}
const _code = sanitizeStatusCode(code, 204);
if (_code === 204) {
event.node.res.removeHeader("content-length");
}
event.node.res.writeHead(_code);
event.node.res.end();
}
function setResponseStatus(event, code, text) {
if (code) {
event.node.res.statusCode = sanitizeStatusCode(
code,
event.node.res.statusCode
);
}
if (text) {
event.node.res.statusMessage = sanitizeStatusMessage(text);
}
}
function getResponseStatus(event) {
return event.node.res.statusCode;
}
function getResponseStatusText(event) {
return event.node.res.statusMessage;
}
function defaultContentType(event, type) {
if (type && event.node.res.statusCode !== 304 && !event.node.res.getHeader("content-type")) {
event.node.res.setHeader("content-type", type);
}
}
function sendRedirect(event, location, code = 302) {
event.node.res.statusCode = sanitizeStatusCode(
code,
event.node.res.statusCode
);
event.node.res.setHeader("location", location);
const encodedLoc = location.replace(/"/g, "%22");
const html = `<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=${encodedLoc}"></head></html>`;
return send(event, html, MIMES.html);
}
function getResponseHeader(event, name) {
return event.node.res.getHeader(name);
}
function setResponseHeaders(event, headers) {
for (const [name, value] of Object.entries(headers)) {
event.node.res.setHeader(
name,
value
);
}
}
const setHeaders = setResponseHeaders;
function setResponseHeader(event, name, value) {
event.node.res.setHeader(name, value);
}
function appendResponseHeader(event, name, value) {
let current = event.node.res.getHeader(name);
if (!current) {
event.node.res.setHeader(name, value);
return;
}
if (!Array.isArray(current)) {
current = [current.toString()];
}
event.node.res.setHeader(name, [...current, value]);
}
function removeResponseHeader(event, name) {
return event.node.res.removeHeader(name);
}
function isStream(data) {
if (!data || typeof data !== "object") {
return false;
}
if (typeof data.pipe === "function") {
if (typeof data._read === "function") {
return true;
}
if (typeof data.abort === "function") {
return true;
}
}
if (typeof data.pipeTo === "function") {
return true;
}
return false;
}
function isWebResponse(data) {
return typeof Response !== "undefined" && data instanceof Response;
}
function sendStream(event, stream) {
if (!stream || typeof stream !== "object") {
throw new Error("[h3] Invalid stream provided.");
}
event.node.res._data = stream;
if (!event.node.res.socket) {
event._handled = true;
return Promise.resolve();
}
if (hasProp(stream, "pipeTo") && typeof stream.pipeTo === "function") {
return stream.pipeTo(
new WritableStream({
write(chunk) {
event.node.res.write(chunk);
}
})
).then(() => {
event.node.res.end();
});
}
if (hasProp(stream, "pipe") && typeof stream.pipe === "function") {
return new Promise((resolve, reject) => {
stream.pipe(event.node.res);
if (stream.on) {
stream.on("end", () => {
event.node.res.end();
resolve();
});
stream.on("error", (error) => {
reject(error);
});
}
event.node.res.on("close", () => {
if (stream.abort) {
stream.abort();
}
});
});
}
throw new Error("[h3] Invalid or incompatible stream provided.");
}
function sendWebResponse(event, response) {
for (const [key, value] of response.headers) {
if (key === "set-cookie") {
event.node.res.appendHeader(key, splitCookiesString(value));
} else {
event.node.res.setHeader(key, value);
}
}
if (response.status) {
event.node.res.statusCode = sanitizeStatusCode(
response.status,
event.node.res.statusCode
);
}
if (response.statusText) {
event.node.res.statusMessage = sanitizeStatusMessage(response.statusText);
}
if (response.redirected) {
event.node.res.setHeader("location", response.url);
}
if (!response.body) {
event.node.res.end();
return;
}
return sendStream(event, response.body);
}
const PayloadMethods = /* @__PURE__ */ new Set(["PATCH", "POST", "PUT", "DELETE"]);
const ignoredHeaders = /* @__PURE__ */ new Set([
"transfer-encoding",
"accept-encoding",
"connection",
"keep-alive",
"upgrade",
"expect",
"host",
"accept"
]);
async function proxyRequest(event, target, opts = {}) {
let body;
let duplex;
if (PayloadMethods.has(event.method)) {
if (opts.streamRequest) {
body = getRequestWebStream(event);
duplex = "half";
} else {
body = await readRawBody(event, false).catch(() => void 0);
}
}
const method = opts.fetchOptions?.method || event.method;
const fetchHeaders = mergeHeaders$1(
getProxyRequestHeaders(event, { host: target.startsWith("/") }),
opts.fetchOptions?.headers,
opts.headers
);
return sendProxy(event, target, {
...opts,
fetchOptions: {
method,
body,
duplex,
...opts.fetchOptions,
headers: fetchHeaders
}
});
}
async function sendProxy(event, target, opts = {}) {
let response;
try {
response = await _getFetch(opts.fetch)(target, {
headers: opts.headers,
ignoreResponseError: true,
// make $ofetch.raw transparent
...opts.fetchOptions
});
} catch (error) {
throw createError$1({
status: 502,
statusMessage: "Bad Gateway",
cause: error
});
}
event.node.res.statusCode = sanitizeStatusCode(
response.status,
event.node.res.statusCode
);
event.node.res.statusMessage = sanitizeStatusMessage(response.statusText);
const cookies = [];
for (const [key, value] of response.headers.entries()) {
if (key === "content-encoding") {
continue;
}
if (key === "content-length") {
continue;
}
if (key === "set-cookie") {
cookies.push(...splitCookiesString(value));
continue;
}
event.node.res.setHeader(key, value);
}
if (cookies.length > 0) {
event.node.res.setHeader(
"set-cookie",
cookies.map((cookie) => {
if (opts.cookieDomainRewrite) {
cookie = rewriteCookieProperty(
cookie,
opts.cookieDomainRewrite,
"domain"
);
}
if (opts.cookiePathRewrite) {
cookie = rewriteCookieProperty(
cookie,
opts.cookiePathRewrite,
"path"
);
}
return cookie;
})
);
}
if (opts.onResponse) {
await opts.onResponse(event, response);
}
if (response._data !== void 0) {
return response._data;
}
if (event.handled) {
return;
}
if (opts.sendStream === false) {
const data = new Uint8Array(await response.arrayBuffer());
return event.node.res.end(data);
}
if (response.body) {
for await (const chunk of response.body) {
event.node.res.write(chunk);
}
}
return event.node.res.end();
}
function getProxyRequestHeaders(event, opts) {
const headers = /* @__PURE__ */ Object.create(null);
const reqHeaders = getRequestHeaders(event);
for (const name in reqHeaders) {
if (!ignoredHeaders.has(name) || name === "host" && opts?.host) {
headers[name] = reqHeaders[name];
}
}
return headers;
}
function fetchWithEvent(event, req, init, options) {
return _getFetch(options?.fetch)(req, {
...init,
context: init?.context || event.context,
headers: {
...getProxyRequestHeaders(event, {
host: typeof req === "string" && req.startsWith("/")
}),
...init?.headers
}
});
}
function _getFetch(_fetch) {
if (_fetch) {
return _fetch;
}
if (globalThis.fetch) {
return globalThis.fetch;
}
throw new Error(
"fetch is not available. Try importing `node-fetch-native/polyfill` for Node.js."
);
}
function rewriteCookieProperty(header, map, property) {
const _map = typeof map === "string" ? { "*": map } : map;
return header.replace(
new RegExp(`(;\\s*${property}=)([^;]+)`, "gi"),
(match, prefix, previousValue) => {
let newValue;
if (previousValue in _map) {
newValue = _map[previousValue];
} else if ("*" in _map) {
newValue = _map["*"];
} else {
return match;
}
return newValue ? prefix + newValue : "";
}
);
}
function mergeHeaders$1(defaults, ...inputs) {
const _inputs = inputs.filter(Boolean);
if (_inputs.length === 0) {
return defaults;
}
const merged = new Headers(defaults);
for (const input of _inputs) {
const entries = Array.isArray(input) ? input : typeof input.entries === "function" ? input.entries() : Object.entries(input);
for (const [key, value] of entries) {
if (value !== void 0) {
merged.set(key, value);
}
}
}
return merged;
}
class H3Event {
"__is_event__" = true;
// Context
node;
// Node
web;
// Web
context = {};
// Shared
// Request
_method;
_path;
_headers;
_requestBody;
// Response
_handled = false;
// Hooks
_onBeforeResponseCalled;
_onAfterResponseCalled;
constructor(req, res) {
this.node = { req, res };
}
// --- Request ---
get method() {
if (!this._method) {
this._method = (this.node.req.method || "GET").toUpperCase();
}
return this._method;
}
get path() {
return this._path || this.node.req.url || "/";
}
get headers() {
if (!this._headers) {
this._headers = _normalizeNodeHeaders(this.node.req.headers);
}
return this._headers;
}
// --- Respoonse ---
get handled() {
return this._handled || this.node.res.writableEnded || this.node.res.headersSent;
}
respondWith(response) {
return Promise.resolve(response).then(
(_response) => sendWebResponse(this, _response)
);
}
// --- Utils ---
toString() {
return `[${this.method}] ${this.path}`;
}
toJSON() {
return this.toString();
}
// --- Deprecated ---
/** @deprecated Please use `event.node.req` instead. */
get req() {
return this.node.req;
}
/** @deprecated Please use `event.node.res` instead. */
get res() {
return this.node.res;
}
}
function isEvent(input) {
return hasProp(input, "__is_event__");
}
function createEvent(req, res) {
return new H3Event(req, res);
}
function _normalizeNodeHeaders(nodeHeaders) {
const headers = new Headers();
for (const [name, value] of Object.entries(nodeHeaders)) {
if (Array.isArray(value)) {
for (const item of value) {
headers.append(name, item);
}
} else if (value) {
headers.set(name, value);
}
}
return headers;
}
function defineEventHandler(handler) {
if (typeof handler === "function") {
handler.__is_handler__ = true;
return handler;
}
const _hooks = {
onRequest: _normalizeArray(handler.onRequest),
onBeforeResponse: _normalizeArray(handler.onBeforeResponse)
};
const _handler = (event) => {
return _callHandler(event, handler.handler, _hooks);
};
_handler.__is_handler__ = true;
_handler.__resolve__ = handler.handler.__resolve__;
_handler.__websocket__ = handler.websocket;
return _handler;
}
function _normalizeArray(input) {
return input ? Array.isArray(input) ? input : [input] : void 0;
}
async function _callHandler(event, handler, hooks) {
if (hooks.onRequest) {
for (const hook of hooks.onRequest) {
await hook(event);
if (event.handled) {
return;
}
}
}
const body = await handler(event);
const response = { body };
if (hooks.onBeforeResponse) {
for (const hook of hooks.onBeforeResponse) {
await hook(event, response);
}
}
return response.body;
}
const eventHandler = defineEventHandler;
function isEventHandler(input) {
return hasProp(input, "__is_handler__");
}
function toEventHandler(input, _, _route) {
return input;
}
function defineLazyEventHandler(factory) {
let _promise;
let _resolved;
const resolveHandler = () => {
if (_resolved) {
return Promise.resolve(_resolved);
}
if (!_promise) {
_promise = Promise.resolve(factory()).then((r) => {
const handler2 = r.default || r;
if (typeof handler2 !== "function") {
throw new TypeError(
"Invalid lazy handler result. It should be a function:",
handler2
);
}
_resolved = { handler: toEventHandler(r.default || r) };
return _resolved;
});
}
return _promise;
};
const handler = eventHandler((event) => {
if (_resolved) {
return _resolved.handler(event);
}
return resolveHandler().then((r) => r.handler(event));
});
handler.__resolve__ = resolveHandler;
return handler;
}
const lazyEventHandler = defineLazyEventHandler;
function createApp(options = {}) {
const stack = [];
const handler = createAppEventHandler(stack, options);
const resolve = createResolver(stack);
handler.__resolve__ = resolve;
const getWebsocket = cachedFn(() => websocketOptions(resolve, options));
const app = {
// @ts-expect-error
use: (arg1, arg2, arg3) => use(app, arg1, arg2, arg3),
resolve,
handler,
stack,
options,
get websocket() {
return getWebsocket();
}
};
return app;
}
function use(app, arg1, arg2, arg3) {
if (Array.isArray(arg1)) {
for (const i of arg1) {
use(app, i, arg2, arg3);
}
} else if (Array.isArray(arg2)) {
for (const i of arg2) {
use(app, arg1, i, arg3);
}
} else if (typeof arg1 === "string") {
app.stack.push(
normalizeLayer({ ...arg3, route: arg1, handler: arg2 })
);
} else if (typeof arg1 === "function") {
app.stack.push(normalizeLayer({ ...arg2, handler: arg1 }));
} else {
app.stack.push(normalizeLayer({ ...arg1 }));
}
return app;
}
function createAppEventHandler(stack, options) {
const spacing = options.debug ? 2 : void 0;
return eventHandler(async (event) => {
event.node.req.originalUrl = event.node.req.originalUrl || event.node.req.url || "/";
const _rawReqUrl = event.node.req.url || "/";
const _reqPath = _decodePath(event._path || _rawReqUrl);
event._path = _reqPath;
const _needsRawUrl = _reqPath !== _rawReqUrl;
let _layerPath;
if (options.onRequest) {
await options.onRequest(event);
}
for (const layer of stack) {
if (layer.route.length > 1) {
if (!_reqPath.startsWith(layer.route)) {
continue;
}
_layerPath = _reqPath.slice(layer.route.length) || "/";
} else {
_layerPath = _reqPath;
}
if (layer.match && !layer.match(_layerPath, event)) {
continue;
}
event._path = _layerPath;
event.node.req.url = _needsRawUrl ? layer.route.length > 1 ? _rawReqUrl.slice(layer.route.length) || "/" : _rawReqUrl : _layerPath;
const val = await layer.handler(event);
const _body = val === void 0 ? void 0 : await val;
if (_body !== void 0) {
const _response = { body: _body };
if (options.onBeforeResponse) {
event._onBeforeResponseCalled = true;
await options.onBeforeResponse(event, _response);
}
await handleHandlerResponse(event, _response.body, spacing);
if (options.onAfterResponse) {
event._onAfterResponseCalled = true;
await options.onAfterResponse(event, _response);
}
return;
}
if (event.handled) {
if (options.onAfterResponse) {
event._onAfterResponseCalled = true;
await options.onAfterResponse(event, void 0);
}
return;
}
}
if (!event.handled) {
throw createError$1({
statusCode: 404,
statusMessage: `Cannot find any path matching ${event.path || "/"}.`
});
}
if (options.onAfterResponse) {
event._onAfterResponseCalled = true;
await options.onAfterResponse(event, void 0);
}
});
}
function createResolver(stack) {
return async (path) => {
let _layerPath;
for (const layer of stack) {
if (layer.route === "/" && !layer.handler.__resolve__) {
continue;
}
if (!path.startsWith(layer.route)) {
continue;
}
_layerPath = path.slice(layer.route.length) || "/";
if (layer.match && !layer.match(_layerPath, void 0)) {
continue;
}
let res = { route: layer.route, handler: layer.handler };
if (res.handler.__resolve__) {
const _res = await res.handler.__resolve__(_layerPath);
if (!_res) {
continue;
}
res = {
...res,
..._res,
route: joinURL(res.route || "/", _res.route || "/")
};
}
return res;
}
};
}
function normalizeLayer(input) {
let handler = input.handler;
if (handler.handler) {
handler = handler.handler;
}
if (input.lazy) {
handler = lazyEventHandler(handler);
} else if (!isEventHandler(handler)) {
handler = toEventHandler(handler, void 0, input.route);
}
return {
route: withoutTrailingSlash(input.route),
match: input.match,
handler
};
}
function handleHandlerResponse(event, val, jsonSpace) {
if (val === null) {
return sendNoContent(event);
}
if (val) {
if (isWebResponse(val)) {
return sendWebResponse(event, val);
}
if (isStream(val)) {
return sendStream(event, val);
}
if (val.buffer) {
return send(event, val);
}
if (val.arrayBuffer && typeof val.arrayBuffer === "function") {
return val.arrayBuffer().then((arrayBuffer) => {
return send(event, Buffer.from(arrayBuffer), val.type);
});
}
if (val instanceof Error) {
throw createError$1(val);
}
if (typeof val.end === "function") {
return true;
}
}
const valType = typeof val;
if (valType === "string") {
return send(event, val, MIMES.html);
}
if (valType === "object" || valType === "boolean" || valType === "number") {
return send(event, JSON.stringify(val, void 0, jsonSpace), MIMES.json);
}
if (valType === "bigint") {
return send(event, val.toString(), MIMES.json);
}
throw createError$1({
statusCode: 500,
statusMessage: `[h3] Cannot send ${valType} as response.`
});
}
function cachedFn(fn) {
let cache;
return () => {
if (!cache) {
cache = fn();
}
return cache;
};
}
function _decodePath(url) {
const qIndex = url.indexOf("?");
const path = qIndex === -1 ? url : url.slice(0, qIndex);
const query = qIndex === -1 ? "" : url.slice(qIndex);
const decodedPath = path.includes("%25") ? decodePath(path.replace(/%25/g, "%2525")) : decodePath(path);
return decodedPath + query;
}
function websocketOptions(evResolver, appOptions) {
return {
...appOptions.websocket,
async resolve(info) {
const url = info.request?.url || info.url || "/";
const { pathname } = typeof url === "string" ? parseURL(url) : url;
const resolved = await evResolver(pathname);
return resolved?.handler?.__websocket__ || {};
}
};
}
const RouterMethods = [
"connect",
"delete",
"get",
"head",
"options",
"post",
"put",
"trace",
"patch"
];
function createRouter(opts = {}) {
const _router = createRouter$1({});
const routes = {};
let _matcher;
const router = {};
const addRoute = (path, handler, method) => {
let route = routes[path];
if (!route) {
routes[path] = route = { path, handlers: {} };
_router.insert(path, route);
}
if (Array.isArray(method)) {
for (const m of method) {
addRoute(path, handler, m);
}
} else {
route.handlers[method] = toEventHandler(handler);
}
return router;
};
router.use = router.add = (path, handler, method) => addRoute(path, handler, method || "all");
for (const method of RouterMethods) {
router[method] = (path, handle) => router.add(path, handle, method);
}
const matchHandler = (path = "/", method = "get") => {
const qIndex = path.indexOf("?");
if (qIndex !== -1) {
path = path.slice(0, Math.max(0, qIndex));
}
const matched = _router.lookup(path);
if (!matched || !matched.handlers) {
return {
error: createError$1({
statusCode: 404,
name: "Not Found",
statusMessage: `Cannot find any route matching ${path || "/"}.`
})
};
}
let handler = matched.handlers[method] || matched.handlers.all;
if (!handler) {
if (!_matcher) {
_matcher = toRouteMatcher(_router);
}
const _matches = _matcher.matchAll(path).reverse();
for (const _match of _matches) {
if (_match.handlers[method]) {
handler = _match.handlers[method];
matched.handlers[method] = matched.handlers[method] || handler;
break;
}
if (_match.handlers.all) {
handler = _match.handlers.all;
matched.handlers.all = matched.handlers.all || handler;
break;
}
}
}
if (!handler) {
return {
error: createError$1({
statusCode: 405,
name: "Method Not Allowed",
statusMessage: `Method ${method} is not allowed on this route.`
})
};
}
return { matched, handler };
};
const isPreemptive = opts.preemptive || opts.preemtive;
router.handler = eventHandler((event) => {
const match = matchHandler(
event.path,
event.method.toLowerCase()
);
if ("error" in match) {
if (isPreemptive) {
throw match.error;
} else {
return;
}
}
event.context.matchedRoute = match.matched;
const params = match.matched.params || {};
event.context.params = params;
return Promise.resolve(match.handler(event)).then((res) => {
if (res === void 0 && isPreemptive) {
return null;
}
return res;
});
});
router.handler.__resolve__ = async (path) => {
path = withLeadingSlash(path);
const match = matchHandler(path);
if ("error" in match) {
return;
}
let res = {
route: match.matched.path,
handler: match.handler
};
if (match.handler.__resolve__) {
const _res = await match.handler.__resolve__(path);
if (!_res) {
return;
}
res = { ...res, ..._res };
}
return res;
};
return router;
}
function toNodeListener(app) {
const toNodeHandle = async function(req, res) {
const event = createEvent(req, res);
try {
await app.handler(event);
} catch (_error) {
const error = createError$1(_error);
if (!isError(_error)) {
error.unhandled = true;
}
setResponseStatus(event, error.statusCode, error.statusMessage);
if (app.options.onError) {
await app.options.onError(error, event);
}
if (event.handled) {
return;
}
if (error.unhandled || error.fatal) {
console.error("[h3]", error.fatal ? "[fatal]" : "[unhandled]", error);
}
if (app.options.onBeforeResponse && !event._onBeforeResponseCalled) {
await app.options.onBeforeResponse(event, { body: error });
}
await sendError(event, error, !!app.options.debug);
if (app.options.onAfterResponse && !event._onAfterResponseCalled) {
await app.options.onAfterResponse(event, { body: error });
}
}
};
return toNodeHandle;
}
function flatHooks(configHooks, hooks = {}, parentName) {
for (const key in configHooks) {
const subHook = configHooks[key];
const name = parentName ? `${parentName}:${key}` : key;
if (typeof subHook === "object" && subHook !== null) {
flatHooks(subHook, hooks, name);
} else if (typeof subHook === "function") {
hooks[name] = subHook;
}
}
return hooks;
}
const defaultTask = { run: (function_) => function_() };
const _createTask = () => defaultTask;
const createTask = typeof console.createTask !== "undefined" ? console.createTask : _createTask;
function serialTaskCaller(hooks, args) {
const name = args.shift();
const task = createTask(name);
return hooks.reduce(
(promise, hookFunction) => promise.then(() => task.run(() => hookFunction(...args))),
Promise.resolve()
);
}
function parallelTaskCaller(hooks, args) {
const name = args.shift();
const task = createTask(name);
return Promise.all(hooks.map((hook) => task.run(() => hook(...args))));
}
function callEachWith(callbacks, arg0) {
for (const callback of [...callbacks]) {
callback(arg0);
}
}
class Hookable {
constructor() {
this._hooks = {};
this._before = void 0;
this._after = void 0;
this._deprecatedMessages = void 0;
this._deprecatedHooks = {};
this.hook = this.hook.bind(this);
this.callHook = this.callHook.bind(this);
this.callHookWith = this.callHookWith.bind(this);
}
hook(name, function_, options = {}) {
if (!name || typeof function_ !== "function") {
return () => {
};
}
const originalName = name;
let dep;
while (this._deprecatedHooks[name]) {
dep = this._deprecatedHooks[name];
name = dep.to;
}
if (dep && !options.allowDeprecated) {
let message = dep.message;
if (!message) {
message = `${originalName} hook has been deprecated` + (dep.to ? `, please use ${dep.to}` : "");
}
if (!this._deprecatedMessages) {
this._deprecatedMessages = /* @__PURE__ */ new Set();
}
if (!this._deprecatedMessages.has(message)) {
console.warn(message);
this._deprecatedMessages.add(message);
}
}
if (!function_.name) {
try {
Object.defineProperty(function_, "name", {
get: () => "_" + name.replace(/\W+/g, "_") + "_hook_cb",
configurable: true
});
} catch {
}
}
this._hooks[name] = this._hooks[name] || [];
this._hooks[name].push(function_);
return () => {
if (function_) {
this.removeHook(name, function_);
function_ = void 0;
}
};
}
hookOnce(name, function_) {
let _unreg;
let _function = (...arguments_) => {
if (typeof _unreg === "function") {
_unreg();
}
_unreg = void 0;
_function = void 0;
return function_(...arguments_);
};
_unreg = this.hook(name, _function);
return _unreg;
}
removeHook(name, function_) {
if (this._hooks[name]) {
const index = this._hooks[name].indexOf(function_);
if (index !== -1) {
this._hooks[name].splice(index, 1);
}
if (this._hooks[name].length === 0) {
delete this._hooks[name];
}
}
}
deprecateHook(name, deprecated) {
this._deprecatedHooks[name] = typeof deprecated === "string" ? { to: deprecated } : deprecated;
const _hooks = this._hooks[name] || [];
delete this._hooks[name];
for (const hook of _hooks) {
this.hook(name, hook);
}
}
deprecateHooks(deprecatedHooks) {
Object.assign(this._deprecatedHooks, deprecatedHooks);
for (const name in deprecatedHooks) {
this.deprecateHook(name, deprecatedHooks[name]);
}
}
addHooks(configHooks) {
const hooks = flatHooks(configHooks);
const removeFns = Object.keys(hooks).map(
(key) => this.hook(key, hooks[key])
);
return () => {
for (const unreg of removeFns.splice(0, removeFns.length)) {
unreg();
}
};
}
removeHooks(configHooks) {
const hooks = flatHooks(configHooks);
for (const key in hooks) {
this.removeHook(key, hooks[key]);
}
}
removeAllHooks() {
for (const key in this._hooks) {
delete this._hooks[key];
}
}
callHook(name, ...arguments_) {
arguments_.unshift(name);
return this.callHookWith(serialTaskCaller, name, ...arguments_);
}
callHookParallel(name, ...arguments_) {
arguments_.unshift(name);
return this.callHookWith(parallelTaskCaller, name, ...arguments_);
}
callHookWith(caller, name, ...arguments_) {
const event = this._before || this._after ? { name, args: arguments_, context: {} } : void 0;
if (this._before) {
callEachWith(this._before, event);
}
const result = caller(
name in this._hooks ? [...this._hooks[name]] : [],
arguments_
);
if (result instanceof Promise) {
return result.finally(() => {
if (this._after && event) {
callEachWith(this._after, event);
}
});
}
if (this._after && event) {
callEachWith(this._after, event);
}
return result;
}
beforeEach(function_) {
this._before = this._before || [];
this._before.push(function_);
return () => {
if (this._before !== void 0) {
const index = this._before.indexOf(function_);
if (index !== -1) {
this._before.splice(index, 1);
}
}
};
}
afterEach(function_) {
this._after = this._after || [];
this._after.push(function_);
return () => {
if (this._after !== void 0) {
const index = this._after.indexOf(function_);
if (index !== -1) {
this._after.splice(index, 1);
}
}
};
}
}
function createHooks() {
return new Hookable();
}
const s$1=globalThis.Headers,i=globalThis.AbortController,l=globalThis.fetch||(()=>{throw new Error("[node-fetch-native] Failed to fetch: `globalThis.fetch` is not available!")});
class FetchError extends Error {
constructor(message, opts) {
super(message, opts);
this.name = "FetchError";
if (opts?.cause && !this.cause) {
this.cause = opts.cause;
}
}
}
function createFetchError(ctx) {
const errorMessage = ctx.error?.message || ctx.error?.toString() || "";
const method = ctx.request?.method || ctx.options?.method || "GET";
const url = ctx.request?.url || String(ctx.request) || "/";
const requestStr = `[${method}] ${JSON.stringify(url)}`;
const statusStr = ctx.response ? `${ctx.response.status} ${ctx.response.statusText}` : "<no response>";
const message = `${requestStr}: ${statusStr}${errorMessage ? ` ${errorMessage}` : ""}`;
const fetchError = new FetchError(
message,
ctx.error ? { cause: ctx.error } : void 0
);
for (const key of ["request", "options", "response"]) {
Object.defineProperty(fetchError, key, {
get() {
return ctx[key];
}
});
}
for (const [key, refKey] of [
["data", "_data"],
["status", "status"],
["statusCode", "status"],
["statusText", "statusText"],
["statusMessage", "statusText"]
]) {
Object.defineProperty(fetchError, key, {
get() {
return ctx.response && ctx.response[refKey];
}
});
}
return fetchError;
}
const payloadMethods = new Set(
Object.freeze(["PATCH", "POST", "PUT", "DELETE"])
);
function isPayloadMethod(method = "GET") {
return payloadMethods.has(method.toUpperCase());
}
function isJSONSerializable(value) {
if (value === void 0) {
return false;
}
const t = typeof value;
if (t === "string" || t === "number" || t === "boolean" || t === null) {
return true;
}
if (t !== "object") {
return false;
}
if (Array.isArray(value)) {
return true;
}
if (value.buffer) {
return false;
}
if (value instanceof FormData || value instanceof URLSearchParams) {
return false;
}
return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function";
}
const textTypes = /* @__PURE__ */ new Set([
"image/svg",
"application/xml",
"application/xhtml",
"application/html"
]);
const JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;
function detectResponseType(_contentType = "") {
if (!_contentType) {
return "json";
}
const contentType = _contentType.split(";").shift() || "";
if (JSON_RE.test(contentType)) {
return "json";
}
if (contentType === "text/event-stream") {
return "stream";
}
if (textTypes.has(contentType) || contentType.startsWith("text/")) {
return "text";
}
return "blob";
}
function resolveFetchOptions(request, input, defaults, Headers) {
const headers = mergeHeaders(
input?.headers ?? request?.headers,
defaults?.headers,
Headers
);
let query;
if (defaults?.query || defaults?.params || input?.params || input?.query) {
query = {
...defaults?.params,
...defaults?.query,
...input?.params,
...input?.query
};
}
return {
...defaults,
...input,
query,
params: query,
headers
};
}
function mergeHeaders(input, defaults, Headers) {
if (!defaults) {
return new Headers(input);
}
const headers = new Headers(defaults);
if (input) {
for (const [key, value] of Symbol.iterator in input || Array.isArray(input) ? input : new Headers(input)) {
headers.set(key, value);
}
}
return headers;
}
async function callHooks(context, hooks) {
if (hooks) {
if (Array.isArray(hooks)) {
for (const hook of hooks) {
await hook(context);
}
} else {
await hooks(context);
}
}
}
const retryStatusCodes = /* @__PURE__ */ new Set([
408,
// Request Timeout
409,
// Conflict
425,
// Too Early (Experimental)
429,
// Too Many Requests
500,
// Internal Server Error
502,
// Bad Gateway
503,
// Service Unavailable
504
// Gateway Timeout
]);
const nullBodyResponses = /* @__PURE__ */ new Set([101, 204, 205, 304]);
function createFetch(globalOptions = {}) {
const {
fetch = globalThis.fetch,
Headers = globalThis.Headers,
AbortController = globalThis.AbortController
} = globalOptions;
async function onError(context) {
const isAbort = context.error && context.error.name === "AbortError" && !context.options.timeout || false;
if (context.options.retry !== false && !isAbort) {
let retries;
if (typeof context.options.retry === "number") {
retries = context.options.retry;
} else {
retries = isPayloadMethod(context.options.method) ? 0 : 1;
}
const responseCode = context.response && context.response.status || 500;
if (retries > 0 && (Array.isArray(context.options.retryStatusCodes) ? context.options.retryStatusCodes.includes(responseCode) : retryStatusCodes.has(responseCode))) {
const retryDelay = typeof context.options.retryDelay === "function" ? context.options.retryDelay(context) : context.options.retryDelay || 0;
if (retryDelay > 0) {
await new Promise((resolve) => setTimeout(resolve, retryDelay));
}
return $fetchRaw(context.request, {
...context.options,
retry: retries - 1
});
}
}
const error = createFetchError(context);
if (Error.captureStackTrace) {
Error.captureStackTrace(error, $fetchRaw);
}
throw error;
}
const $fetchRaw = async function $fetchRaw2(_request, _options = {}) {
const context = {
request: _request,
options: resolveFetchOptions(
_request,
_options,
globalOptions.defaults,
Headers
),
response: void 0,
error: void 0
};
if (context.options.method) {
context.options.method = context.options.method.toUpperCase();
}
if (context.options.onRequest) {
await callHooks(context, context.options.onRequest);
if (!(context.options.headers instanceof Headers)) {
context.options.headers = new Headers(
context.options.headers || {}
/* compat */
);
}
}
if (typeof context.request === "string") {
if (context.options.baseURL) {
context.request = withBase(context.request, context.options.baseURL);
}
if (context.options.query) {
context.request = withQuery(context.request, context.options.query);
delete context.options.query;
}
if ("query" in context.options) {
delete context.options.query;
}
if ("params" in context.options) {
delete context.options.params;
}
}
if (context.options.body && isPayloadMethod(context.options.method)) {
if (isJSONSerializable(context.options.body)) {
const contentType = context.options.headers.get("content-type");
if (typeof context.options.body !== "string") {
context.options.body = contentType === "application/x-www-form-urlencoded" ? new URLSearchParams(
context.options.body
).toString() : JSON.stringify(context.options.body);
}
if (!contentType) {
context.options.headers.set("content-type", "application/json");
}
if (!context.options.headers.has("accept")) {
context.options.headers.set("accept", "application/json");
}
} else if (
// ReadableStream Body
"pipeTo" in context.options.body && typeof context.options.body.pipeTo === "function" || // Node.js Stream Body
typeof context.options.body.pipe === "function"
) {
if (!("duplex" in context.options)) {
context.options.duplex = "half";
}
}
}
let abortTimeout;
if (!context.options.signal && context.options.timeout) {
const controller = new AbortController();
abortTimeout = setTimeout(() => {
const error = new Error(
"[TimeoutError]: The operation was aborted due to timeout"
);
error.name = "TimeoutError";
error.code = 23;
controller.abort(error);
}, context.options.timeout);
context.options.signal = controller.signal;
}
try {
context.response = await fetch(
context.request,
context.options
);
} catch (error) {
context.error = error;
if (context.options.onRequestError) {
await callHooks(
context,
context.options.onRequestError
);
}
return await onError(context);
} finally {
if (abortTimeout) {
clearTimeout(abortTimeout);
}
}
const hasBody = (context.response.body || // https://github.com/unjs/ofetch/issues/324
// https://github.com/unjs/ofetch/issues/294
// https://github.com/JakeChampion/fetch/issues/1454
context.response._bodyInit) && !nullBodyResponses.has(context.response.status) && context.options.method !== "HEAD";
if (hasBody) {
const responseType = (context.options.parseResponse ? "json" : context.options.responseType) || detectResponseType(context.response.headers.get("content-type") || "");
switch (responseType) {
case "json": {
const data = await context.response.text();
const parseFunction = context.options.parseResponse || destr;
context.response._data = parseFunction(data);
break;
}
case "stream": {
context.response._data = context.response.body || context.response._bodyInit;
break;
}
default: {
context.response._data = await context.response[responseType]();
}
}
}
if (context.options.onResponse) {
await callHooks(
context,
context.options.onResponse
);
}
if (!context.options.ignoreResponseError && context.response.status >= 400 && context.response.status < 600) {
if (context.options.onResponseError) {
await callHooks(
context,
context.options.onResponseError
);
}
return await onError(context);
}
return context.response;
};
const $fetch = async function $fetch2(request, options) {
const r = await $fetchRaw(request, options);
return r._data;
};
$fetch.raw = $fetchRaw;
$fetch.native = (...args) => fetch(...args);
$fetch.create = (defaultOptions = {}, customGlobalOptions = {}) => createFetch({
...globalOptions,
...customGlobalOptions,
defaults: {
...globalOptions.defaults,
...customGlobalOptions.defaults,
...defaultOptions
}
});
return $fetch;
}
function createNodeFetch() {
const useKeepAlive = JSON.parse(process.env.FETCH_KEEP_ALIVE || "false");
if (!useKeepAlive) {
return l;
}
const agentOptions = { keepAlive: true };
const httpAgent = new http.Agent(agentOptions);
const httpsAgent = new https.Agent(agentOptions);
const nodeFetchOptions = {
agent(parsedURL) {
return parsedURL.protocol === "http:" ? httpAgent : httpsAgent;
}
};
return function nodeFetchWithKeepAlive(input, init) {
return l(input, { ...nodeFetchOptions, ...init });
};
}
const fetch = globalThis.fetch ? (...args) => globalThis.fetch(...args) : createNodeFetch();
const Headers$1 = globalThis.Headers || s$1;
const AbortController = globalThis.AbortController || i;
const ofetch = createFetch({ fetch, Headers: Headers$1, AbortController });
const $fetch$1 = ofetch;
function wrapToPromise(value) {
if (!value || typeof value.then !== "function") {
return Promise.resolve(value);
}
return value;
}
function asyncCall(function_, ...arguments_) {
try {
return wrapToPromise(function_(...arguments_));
} catch (error) {
return Promise.reject(error);
}
}
function isPrimitive(value) {
const type = typeof value;
return value === null || type !== "object" && type !== "function";
}
function isPureObject(value) {
const proto = Object.getPrototypeOf(value);
return !proto || proto.isPrototypeOf(Object);
}
function stringify(value) {
if (isPrimitive(value)) {
return String(value);
}
if (isPureObject(value) || Array.isArray(value)) {
return JSON.stringify(value);
}
if (typeof value.toJSON === "function") {
return stringify(value.toJSON());
}
throw new Error("[unstorage] Cannot stringify value!");
}
const BASE64_PREFIX = "base64:";
function serializeRaw(value) {
if (typeof value === "string") {
return value;
}
return BASE64_PREFIX + base64Encode(value);
}
function deserializeRaw(value) {
if (typeof value !== "string") {
return value;
}
if (!value.startsWith(BASE64_PREFIX)) {
return value;
}
return base64Decode(value.slice(BASE64_PREFIX.length));
}
function base64Decode(input) {
if (globalThis.Buffer) {
return Buffer.from(input, "base64");
}
return Uint8Array.from(
globalThis.atob(input),
(c) => c.codePointAt(0)
);
}
function base64Encode(input) {
if (globalThis.Buffer) {
return Buffer.from(input).toString("base64");
}
return globalThis.btoa(String.fromCodePoint(...input));
}
const storageKeyProperties = [
"has",
"hasItem",
"get",
"getItem",
"getItemRaw",
"set",
"setItem",
"setItemRaw",
"del",
"remove",
"removeItem",
"getMeta",
"setMeta",
"removeMeta",
"getKeys",
"clear",
"mount",
"unmount"
];
function prefixStorage(storage, base) {
base = normalizeBaseKey(base);
if (!base) {
return storage;
}
const nsStorage = { ...storage };
for (const property of storageKeyProperties) {
nsStorage[property] = (key = "", ...args) => (
// @ts-ignore
storage[property](base + key, ...args)
);
}
nsStorage.getKeys = (key = "", ...arguments_) => storage.getKeys(base + key, ...arguments_).then((keys) => keys.map((key2) => key2.slice(base.length)));
nsStorage.keys = nsStorage.getKeys;
nsStorage.getItems = async (items, commonOptions) => {
const prefixedItems = items.map(
(item) => typeof item === "string" ? base + item : { ...item, key: base + item.key }
);
const results = await storage.getItems(prefixedItems, commonOptions);
return results.map((entry) => ({
key: entry.key.slice(base.length),
value: entry.value
}));
};
nsStorage.setItems = async (items, commonOptions) => {
const prefixedItems = items.map((item) => ({
key: base + item.key,
value: item.value,
options: item.options
}));
return storage.setItems(prefixedItems, commonOptions);
};
return nsStorage;
}
function normalizeKey$1(key) {
if (!key) {
return "";
}
return key.split("?")[0]?.replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, "") || "";
}
function joinKeys(...keys) {
return normalizeKey$1(keys.join(":"));
}
function normalizeBaseKey(base) {
base = normalizeKey$1(base);
return base ? base + ":" : "";
}
function filterKeyByDepth(key, depth) {
if (depth === void 0) {
return true;
}
let substrCount = 0;
let index = key.indexOf(":");
while (index > -1) {
substrCount++;
index = key.indexOf(":", index + 1);
}
return substrCount <= depth;
}
function filterKeyByBase(key, base) {
if (base) {
return key.startsWith(base) && key[key.length - 1] !== "$";
}
return key[key.length - 1] !== "$";
}
function defineDriver$1(factory) {
return factory;
}
const DRIVER_NAME$1 = "memory";
const memory = defineDriver$1(() => {
const data = /* @__PURE__ */ new Map();
return {
name: DRIVER_NAME$1,
getInstance: () => data,
hasItem(key) {
return data.has(key);
},
getItem(key) {
return data.get(key) ?? null;
},
getItemRaw(key) {
return data.get(key) ?? null;
},
setItem(key, value) {
data.set(key, value);
},
setItemRaw(key, value) {
data.set(key, value);
},
removeItem(key) {
data.delete(key);
},
getKeys() {
return [...data.keys()];
},
clear() {
data.clear();
},
dispose() {
data.clear();
}
};
});
function createStorage(options = {}) {
const context = {
mounts: { "": options.driver || memory() },
mountpoints: [""],
watching: false,
watchListeners: [],
unwatch: {}
};
const getMount = (key) => {
for (const base of context.mountpoints) {
if (key.startsWith(base)) {
return {
base,
relativeKey: key.slice(base.length),
driver: context.mounts[base]
};
}
}
return {
base: "",
relativeKey: key,
driver: context.mounts[""]
};
};
const getMounts = (base, includeParent) => {
return context.mountpoints.filter(
(mountpoint) => mountpoint.startsWith(base) || includeParent && base.startsWith(mountpoint)
).map((mountpoint) => ({
relativeBase: base.length > mountpoint.length ? base.slice(mountpoint.length) : void 0,
mountpoint,
driver: context.mounts[mountpoint]
}));
};
const onChange = (event, key) => {
if (!context.watching) {
return;
}
key = normalizeKey$1(key);
for (const listener of context.watchListeners) {
listener(event, key);
}
};
const startWatch = async () => {
if (context.watching) {
return;
}
context.watching = true;
for (const mountpoint in context.mounts) {
context.unwatch[mountpoint] = await watch(
context.mounts[mountpoint],
onChange,
mountpoint
);
}
};
const stopWatch = async () => {
if (!context.watching) {
return;
}
for (const mountpoint in context.unwatch) {
await context.unwatch[mountpoint]();
}
context.unwatch = {};
context.watching = false;
};
const runBatch = (items, commonOptions, cb) => {
const batches = /* @__PURE__ */ new Map();
const getBatch = (mount) => {
let batch = batches.get(mount.base);
if (!batch) {
batch = {
driver: mount.driver,
base: mount.base,
items: []
};
batches.set(mount.base, batch);
}
return batch;
};
for (const item of items) {
const isStringItem = typeof item === "string";
const key = normalizeKey$1(isStringItem ? item : item.key);
const value = isStringItem ? void 0 : item.value;
const options2 = isStringItem || !item.options ? commonOptions : { ...commonOptions, ...item.options };
const mount = getMount(key);
getBatch(mount).items.push({
key,
value,
relativeKey: mount.relativeKey,
options: options2
});
}
return Promise.all([...batches.values()].map((batch) => cb(batch))).then(
(r) => r.flat()
);
};
const storage = {
// Item
hasItem(key, opts = {}) {
key = normalizeKey$1(key);
const { relativeKey, driver } = getMount(key);
return asyncCall(driver.hasItem, relativeKey, opts);
},
getItem(key, opts = {}) {
key = normalizeKey$1(key);
const { relativeKey, driver } = getMount(key);
return asyncCall(driver.getItem, relativeKey, opts).then(
(value) => destr(value)
);
},
getItems(items, commonOptions = {}) {
return runBatch(items, commonOptions, (batch) => {
if (batch.driver.getItems) {
return asyncCall(
batch.driver.getItems,
batch.items.map((item) => ({
key: item.relativeKey,
options: item.options
})),
commonOptions
).then(
(r) => r.map((item) => ({
key: joinKeys(batch.base, item.key),
value: destr(item.value)
}))
);
}
return Promise.all(
batch.items.map((item) => {
return asyncCall(
batch.driver.getItem,
item.relativeKey,
item.options
).then((value) => ({
key: item.key,
value: destr(value)
}));
})
);
});
},
getItemRaw(key, opts = {}) {
key = normalizeKey$1(key);
const { relativeKey, driver } = getMount(key);
if (driver.getItemRaw) {
return asyncCall(driver.getItemRaw, relativeKey, opts);
}
return asyncCall(driver.getItem, relativeKey, opts).then(
(value) => deserializeRaw(value)
);
},
async setItem(key, value, opts = {}) {
if (value === void 0) {
return storage.removeItem(key);
}
key = normalizeKey$1(key);
const { relativeKey, driver } = getMount(key);
if (!driver.setItem) {
return;
}
await asyncCall(driver.setItem, relativeKey, stringify(value), opts);
if (!driver.watch) {
onChange("update", key);
}
},
async setItems(items, commonOptions) {
await runBatch(items, commonOptions, async (batch) => {
if (batch.driver.setItems) {
return asyncCall(
batch.driver.setItems,
batch.items.map((item) => ({
key: item.relativeKey,
value: stringify(item.value),
options: item.options
})),
commonOptions
);
}
if (!batch.driver.setItem) {
return;
}
await Promise.all(
batch.items.map((item) => {
return asyncCall(
batch.driver.setItem,
item.relativeKey,
stringify(item.value),
item.options
);
})
);
});
},
async setItemRaw(key, value, opts = {}) {
if (value === void 0) {
return storage.removeItem(key, opts);
}
key = normalizeKey$1(key);
const { relativeKey, driver } = getMount(key);
if (driver.setItemRaw) {
await asyncCall(driver.setItemRaw, relativeKey, value, opts);
} else if (driver.setItem) {
await asyncCall(driver.setItem, relativeKey, serializeRaw(value), opts);
} else {
return;
}
if (!driver.watch) {
onChange("update", key);
}
},
async removeItem(key, opts = {}) {
if (typeof opts === "boolean") {
opts = { removeMeta: opts };
}
key = normalizeKey$1(key);
const { relativeKey, driver } = getMount(key);
if (!driver.removeItem) {
return;
}
await asyncCall(driver.removeItem, relativeKey, opts);
if (opts.removeMeta || opts.removeMata) {
await asyncCall(driver.removeItem, relativeKey + "$", opts);
}
if (!driver.watch) {
onChange("remove", key);
}
},
// Meta
async getMeta(key, opts = {}) {
if (typeof opts === "boolean") {
opts = { nativeOnly: opts };
}
key = normalizeKey$1(key);
const { relativeKey, driver } = getMount(key);
const meta = /* @__PURE__ */ Object.create(null);
if (driver.getMeta) {
Object.assign(meta, await asyncCall(driver.getMeta, relativeKey, opts));
}
if (!opts.nativeOnly) {
const value = await asyncCall(
driver.getItem,
relativeKey + "$",
opts
).then((value_) => destr(value_));
if (value && typeof value === "object") {
if (typeof value.atime === "string") {
value.atime = new Date(value.atime);
}
if (typeof value.mtime === "string") {
value.mtime = new Date(value.mtime);
}
Object.assign(meta, value);
}
}
return meta;
},
setMeta(key, value, opts = {}) {
return this.setItem(key + "$", value, opts);
},
removeMeta(key, opts = {}) {
return this.removeItem(key + "$", opts);
},
// Keys
async getKeys(base, opts = {}) {
base = normalizeBaseKey(base);
const mounts = getMounts(base, true);
let maskedMounts = [];
const allKeys = [];
let allMountsSupportMaxDepth = true;
for (const mount of mounts) {
if (!mount.driver.flags?.maxDepth) {
allMountsSupportMaxDepth = false;
}
const rawKeys = await asyncCall(
mount.driver.getKeys,
mount.relativeBase,
opts
);
for (const key of rawKeys) {
const fullKey = mount.mountpoint + normalizeKey$1(key);
if (!maskedMounts.some((p) => fullKey.startsWith(p))) {
allKeys.push(fullKey);
}
}
maskedMounts = [
mount.mountpoint,
...maskedMounts.filter((p) => !p.startsWith(mount.mountpoint))
];
}
const shouldFilterByDepth = opts.maxDepth !== void 0 && !allMountsSupportMaxDepth;
return allKeys.filter(
(key) => (!shouldFilterByDepth || filterKeyByDepth(key, opts.maxDepth)) && filterKeyByBase(key, base)
);
},
// Utils
async clear(base, opts = {}) {
base = normalizeBaseKey(base);
await Promise.all(
getMounts(base, false).map(async (m) => {
if (m.driver.clear) {
return asyncCall(m.driver.clear, m.relativeBase, opts);
}
if (m.driver.removeItem) {
const keys = await m.driver.getKeys(m.relativeBase || "", opts);
return Promise.all(
keys.map((key) => m.driver.removeItem(key, opts))
);
}
})
);
},
async dispose() {
await Promise.all(
Object.values(context.mounts).map((driver) => dispose(driver))
);
},
async watch(callback) {
await startWatch();
context.watchListeners.push(callback);
return async () => {
context.watchListeners = context.watchListeners.filter(
(listener) => listener !== callback
);
if (context.watchListeners.length === 0) {
await stopWatch();
}
};
},
async unwatch() {
context.watchListeners = [];
await stopWatch();
},
// Mount
mount(base, driver) {
base = normalizeBaseKey(base);
if (base && context.mounts[base]) {
throw new Error(`already mounted at ${base}`);
}
if (base) {
context.mountpoints.push(base);
context.mountpoints.sort((a, b) => b.length - a.length);
}
context.mounts[base] = driver;
if (context.watching) {
Promise.resolve(watch(driver, onChange, base)).then((unwatcher) => {
context.unwatch[base] = unwatcher;
}).catch(console.error);
}
return storage;
},
async unmount(base, _dispose = true) {
base = normalizeBaseKey(base);
if (!base || !context.mounts[base]) {
return;
}
if (context.watching && base in context.unwatch) {
context.unwatch[base]?.();
delete context.unwatch[base];
}
if (_dispose) {
await dispose(context.mounts[base]);
}
context.mountpoints = context.mountpoints.filter((key) => key !== base);
delete context.mounts[base];
},
getMount(key = "") {
key = normalizeKey$1(key) + ":";
const m = getMount(key);
return {
driver: m.driver,
base: m.base
};
},
getMounts(base = "", opts = {}) {
base = normalizeKey$1(base);
const mounts = getMounts(base, opts.parents);
return mounts.map((m) => ({
driver: m.driver,
base: m.mountpoint
}));
},
// Aliases
keys: (base, opts = {}) => storage.getKeys(base, opts),
get: (key, opts = {}) => storage.getItem(key, opts),
set: (key, value, opts = {}) => storage.setItem(key, value, opts),
has: (key, opts = {}) => storage.hasItem(key, opts),
del: (key, opts = {}) => storage.removeItem(key, opts),
remove: (key, opts = {}) => storage.removeItem(key, opts)
};
return storage;
}
function watch(driver, onChange, base) {
return driver.watch ? driver.watch((event, key) => onChange(event, base + key)) : () => {
};
}
async function dispose(driver) {
if (typeof driver.dispose === "function") {
await asyncCall(driver.dispose);
}
}
const _assets = {
};
const normalizeKey = function normalizeKey(key) {
if (!key) {
return "";
}
return key.split("?")[0]?.replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, "") || "";
};
const assets$1 = {
getKeys() {
return Promise.resolve(Object.keys(_assets))
},
hasItem (id) {
id = normalizeKey(id);
return Promise.resolve(id in _assets)
},
getItem (id) {
id = normalizeKey(id);
return Promise.resolve(_assets[id] ? _assets[id].import() : null)
},
getMeta (id) {
id = normalizeKey(id);
return Promise.resolve(_assets[id] ? _assets[id].meta : {})
}
};
function defineDriver(factory) {
return factory;
}
function createError(driver, message, opts) {
const err = new Error(`[unstorage] [${driver}] ${message}`, opts);
if (Error.captureStackTrace) {
Error.captureStackTrace(err, createError);
}
return err;
}
function createRequiredError(driver, name) {
if (Array.isArray(name)) {
return createError(
driver,
`Missing some of the required options ${name.map((n) => "`" + n + "`").join(", ")}`
);
}
return createError(driver, `Missing required option \`${name}\`.`);
}
function ignoreNotfound(err) {
return err.code === "ENOENT" || err.code === "EISDIR" ? null : err;
}
function ignoreExists(err) {
return err.code === "EEXIST" ? null : err;
}
async function writeFile(path, data, encoding) {
await ensuredir(dirname$1(path));
return promises.writeFile(path, data, encoding);
}
function readFile(path, encoding) {
return promises.readFile(path, encoding).catch(ignoreNotfound);
}
function unlink(path) {
return promises.unlink(path).catch(ignoreNotfound);
}
function readdir(dir) {
return promises.readdir(dir, { withFileTypes: true }).catch(ignoreNotfound).then((r) => r || []);
}
async function ensuredir(dir) {
if (existsSync(dir)) {
return;
}
await ensuredir(dirname$1(dir)).catch(ignoreExists);
await promises.mkdir(dir).catch(ignoreExists);
}
async function readdirRecursive(dir, ignore, maxDepth) {
if (ignore && ignore(dir)) {
return [];
}
const entries = await readdir(dir);
const files = [];
await Promise.all(
entries.map(async (entry) => {
const entryPath = resolve$1(dir, entry.name);
if (entry.isDirectory()) {
if (maxDepth === void 0 || maxDepth > 0) {
const dirFiles = await readdirRecursive(
entryPath,
ignore,
maxDepth === void 0 ? void 0 : maxDepth - 1
);
files.push(...dirFiles.map((f) => entry.name + "/" + f));
}
} else {
if (!(ignore && ignore(entry.name))) {
files.push(entry.name);
}
}
})
);
return files;
}
async function rmRecursive(dir) {
const entries = await readdir(dir);
await Promise.all(
entries.map((entry) => {
const entryPath = resolve$1(dir, entry.name);
if (entry.isDirectory()) {
return rmRecursive(entryPath).then(() => promises.rmdir(entryPath));
} else {
return promises.unlink(entryPath);
}
})
);
}
const PATH_TRAVERSE_RE = /\.\.:|\.\.$/;
const DRIVER_NAME = "fs-lite";
const unstorage_47drivers_47fs_45lite = defineDriver((opts = {}) => {
if (!opts.base) {
throw createRequiredError(DRIVER_NAME, "base");
}
opts.base = resolve$1(opts.base);
const r = (key) => {
if (PATH_TRAVERSE_RE.test(key)) {
throw createError(
DRIVER_NAME,
`Invalid key: ${JSON.stringify(key)}. It should not contain .. segments`
);
}
const resolved = join(opts.base, key.replace(/:/g, "/"));
return resolved;
};
return {
name: DRIVER_NAME,
options: opts,
flags: {
maxDepth: true
},
hasItem(key) {
return existsSync(r(key));
},
getItem(key) {
return readFile(r(key), "utf8");
},
getItemRaw(key) {
return readFile(r(key));
},
async getMeta(key) {
const { atime, mtime, size, birthtime, ctime } = await promises.stat(r(key)).catch(() => ({}));
return { atime, mtime, size, birthtime, ctime };
},
setItem(key, value) {
if (opts.readOnly) {
return;
}
return writeFile(r(key), value, "utf8");
},
setItemRaw(key, value) {
if (opts.readOnly) {
return;
}
return writeFile(r(key), value);
},
removeItem(key) {
if (opts.readOnly) {
return;
}
return unlink(r(key));
},
getKeys(_base, topts) {
return readdirRecursive(r("."), opts.ignore, topts?.maxDepth);
},
async clear() {
if (opts.readOnly || opts.noClear) {
return;
}
await rmRecursive(r("."));
}
};
});
const storage$1 = createStorage({});
storage$1.mount('/assets', assets$1);
storage$1.mount('data', unstorage_47drivers_47fs_45lite({"driver":"fsLite","base":"./.data/kv"}));
function useStorage(base = "") {
return base ? prefixStorage(storage$1, base) : storage$1;
}
function serialize$1(o){return typeof o=="string"?`'${o}'`:new c().serialize(o)}const c=/*@__PURE__*/function(){class o{#t=new Map;compare(t,r){const e=typeof t,n=typeof r;return e==="string"&&n==="string"?t.localeCompare(r):e==="number"&&n==="number"?t-r:String.prototype.localeCompare.call(this.serialize(t,true),this.serialize(r,true))}serialize(t,r){if(t===null)return "null";switch(typeof t){case "string":return r?t:`'${t}'`;case "bigint":return `${t}n`;case "object":return this.$object(t);case "function":return this.$function(t)}return String(t)}serializeObject(t){const r=Object.prototype.toString.call(t);if(r!=="[object Object]")return this.serializeBuiltInType(r.length<10?`unknown:${r}`:r.slice(8,-1),t);const e=t.constructor,n=e===Object||e===void 0?"":e.name;if(n!==""&&globalThis[n]===e)return this.serializeBuiltInType(n,t);if(typeof t.toJSON=="function"){const i=t.toJSON();return n+(i!==null&&typeof i=="object"?this.$object(i):`(${this.serialize(i)})`)}return this.serializeObjectEntries(n,Object.entries(t))}serializeBuiltInType(t,r){const e=this["$"+t];if(e)return e.call(this,r);if(typeof r?.entries=="function")return this.serializeObjectEntries(t,r.entries());throw new Error(`Cannot serialize ${t}`)}serializeObjectEntries(t,r){const e=Array.from(r).sort((i,a)=>this.compare(i[0],a[0]));let n=`${t}{`;for(let i=0;i<e.length;i++){const[a,l]=e[i];n+=`${this.serialize(a,true)}:${this.serialize(l)}`,i<e.length-1&&(n+=",");}return n+"}"}$object(t){let r=this.#t.get(t);return r===void 0&&(this.#t.set(t,`#${this.#t.size}`),r=this.serializeObject(t),this.#t.set(t,r)),r}$function(t){const r=Function.prototype.toString.call(t);return r.slice(-15)==="[native code] }"?`${t.name||""}()[native]`:`${t.name}(${t.length})${r.replace(/\s*\n\s*/g,"")}`}$Array(t){let r="[";for(let e=0;e<t.length;e++)r+=this.serialize(t[e]),e<t.length-1&&(r+=",");return r+"]"}$Date(t){try{return `Date(${t.toISOString()})`}catch{return "Date(null)"}}$ArrayBuffer(t){return `ArrayBuffer[${new Uint8Array(t).join(",")}]`}$Set(t){return `Set${this.$Array(Array.from(t).sort((r,e)=>this.compare(r,e)))}`}$Map(t){return this.serializeObjectEntries("Map",t.entries())}}for(const s of ["Error","RegExp","URL"])o.prototype["$"+s]=function(t){return `${s}(${t})`};for(const s of ["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array"])o.prototype["$"+s]=function(t){return `${s}[${t.join(",")}]`};for(const s of ["BigInt64Array","BigUint64Array"])o.prototype["$"+s]=function(t){return `${s}[${t.join("n,")}${t.length>0?"n":""}]`};return o}();
function isEqual(object1, object2) {
if (object1 === object2) {
return true;
}
if (serialize$1(object1) === serialize$1(object2)) {
return true;
}
return false;
}
const e=globalThis.process?.getBuiltinModule?.("crypto")?.hash,r="sha256",s="base64url";function digest(t){if(e)return e(r,t,s);const o=createHash(r).update(t);return globalThis.process?.versions?.webcontainer?o.digest().toString(s):o.digest(s)}
const Hasher = /* @__PURE__ */ (() => {
class Hasher2 {
buff = "";
#context = /* @__PURE__ */ new Map();
write(str) {
this.buff += str;
}
dispatch(value) {
const type = value === null ? "null" : typeof value;
return this[type](value);
}
object(object) {
if (object && typeof object.toJSON === "function") {
return this.object(object.toJSON());
}
const objString = Object.prototype.toString.call(object);
let objType = "";
const objectLength = objString.length;
objType = objectLength < 10 ? "unknown:[" + objString + "]" : objString.slice(8, objectLength - 1);
objType = objType.toLowerCase();
let objectNumber = null;
if ((objectNumber = this.#context.get(object)) === void 0) {
this.#context.set(object, this.#context.size);
} else {
return this.dispatch("[CIRCULAR:" + objectNumber + "]");
}
if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) {
this.write("buffer:");
return this.write(object.toString("utf8"));
}
if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") {
if (this[objType]) {
this[objType](object);
} else {
this.unknown(object, objType);
}
} else {
const keys = Object.keys(object).sort();
const extraKeys = [];
this.write("object:" + (keys.length + extraKeys.length) + ":");
const dispatchForKey = (key) => {
this.dispatch(key);
this.write(":");
this.dispatch(object[key]);
this.write(",");
};
for (const key of keys) {
dispatchForKey(key);
}
for (const key of extraKeys) {
dispatchForKey(key);
}
}
}
array(arr, unordered) {
unordered = unordered === void 0 ? false : unordered;
this.write("array:" + arr.length + ":");
if (!unordered || arr.length <= 1) {
for (const entry of arr) {
this.dispatch(entry);
}
return;
}
const contextAdditions = /* @__PURE__ */ new Map();
const entries = arr.map((entry) => {
const hasher = new Hasher2();
hasher.dispatch(entry);
for (const [key, value] of hasher.#context) {
contextAdditions.set(key, value);
}
return hasher.toString();
});
this.#context = contextAdditions;
entries.sort();
return this.array(entries, false);
}
date(date) {
return this.write("date:" + date.toJSON());
}
symbol(sym) {
return this.write("symbol:" + sym.toString());
}
unknown(value, type) {
this.write(type);
if (!value) {
return;
}
this.write(":");
if (value && typeof value.entries === "function") {
return this.array(
[...value.entries()],
true
/* ordered */
);
}
}
error(err) {
return this.write("error:" + err.toString());
}
boolean(bool) {
return this.write("bool:" + bool);
}
string(string) {
this.write("string:" + string.length + ":");
this.write(string);
}
function(fn) {
this.write("fn:");
if (isNativeFunction(fn)) {
this.dispatch("[native]");
} else {
this.dispatch(fn.toString());
}
}
number(number) {
return this.write("number:" + number);
}
null() {
return this.write("Null");
}
undefined() {
return this.write("Undefined");
}
regexp(regex) {
return this.write("regex:" + regex.toString());
}
arraybuffer(arr) {
this.write("arraybuffer:");
return this.dispatch(new Uint8Array(arr));
}
url(url) {
return this.write("url:" + url.toString());
}
map(map) {
this.write("map:");
const arr = [...map];
return this.array(arr, false);
}
set(set) {
this.write("set:");
const arr = [...set];
return this.array(arr, false);
}
bigint(number) {
return this.write("bigint:" + number.toString());
}
}
for (const type of [
"uint8array",
"uint8clampedarray",
"unt8array",
"uint16array",
"unt16array",
"uint32array",
"unt32array",
"float32array",
"float64array"
]) {
Hasher2.prototype[type] = function(arr) {
this.write(type + ":");
return this.array([...arr], false);
};
}
function isNativeFunction(f) {
if (typeof f !== "function") {
return false;
}
return Function.prototype.toString.call(f).slice(
-15
/* "[native code] }".length */
) === "[native code] }";
}
return Hasher2;
})();
function serialize(object) {
const hasher = new Hasher();
hasher.dispatch(object);
return hasher.buff;
}
function hash(value) {
return digest(typeof value === "string" ? value : serialize(value)).replace(/[-_]/g, "").slice(0, 10);
}
function defaultCacheOptions() {
return {
name: "_",
base: "/cache",
swr: true,
maxAge: 1
};
}
function defineCachedFunction(fn, opts = {}) {
opts = { ...defaultCacheOptions(), ...opts };
const pending = {};
const group = opts.group || "nitro/functions";
const name = opts.name || fn.name || "_";
const integrity = opts.integrity || hash([fn, opts]);
const validate = opts.validate || ((entry) => entry.value !== void 0);
async function get(key, resolver, shouldInvalidateCache, event) {
const cacheKey = [opts.base, group, name, key + ".json"].filter(Boolean).join(":").replace(/:\/$/, ":index");
let entry = await useStorage().getItem(cacheKey).catch((error) => {
console.error(`[cache] Cache read error.`, error);
useNitroApp().captureError(error, { event, tags: ["cache"] });
}) || {};
if (typeof entry !== "object") {
entry = {};
const error = new Error("Malformed data read from cache.");
console.error("[cache]", error);
useNitroApp().captureError(error, { event, tags: ["cache"] });
}
const ttl = (opts.maxAge ?? 0) * 1e3;
if (ttl) {
entry.expires = Date.now() + ttl;
}
const expired = shouldInvalidateCache || entry.integrity !== integrity || ttl && Date.now() - (entry.mtime || 0) > ttl || validate(entry) === false;
const _resolve = async () => {
const isPending = pending[key];
if (!isPending) {
if (entry.value !== void 0 && (opts.staleMaxAge || 0) >= 0 && opts.swr === false) {
entry.value = void 0;
entry.integrity = void 0;
entry.mtime = void 0;
entry.expires = void 0;
}
pending[key] = Promise.resolve(resolver());
}
try {
entry.value = await pending[key];
} catch (error) {
if (!isPending) {
delete pending[key];
}
throw error;
}
if (!isPending) {
entry.mtime = Date.now();
entry.integrity = integrity;
delete pending[key];
if (validate(entry) !== false) {
let setOpts;
if (opts.maxAge && !opts.swr) {
setOpts = { ttl: opts.maxAge };
}
const promise = useStorage().setItem(cacheKey, entry, setOpts).catch((error) => {
console.error(`[cache] Cache write error.`, error);
useNitroApp().captureError(error, { event, tags: ["cache"] });
});
if (event?.waitUntil) {
event.waitUntil(promise);
}
}
}
};
const _resolvePromise = expired ? _resolve() : Promise.resolve();
if (entry.value === void 0) {
await _resolvePromise;
} else if (expired && event && event.waitUntil) {
event.waitUntil(_resolvePromise);
}
if (opts.swr && validate(entry) !== false) {
_resolvePromise.catch((error) => {
console.error(`[cache] SWR handler error.`, error);
useNitroApp().captureError(error, { event, tags: ["cache"] });
});
return entry;
}
return _resolvePromise.then(() => entry);
}
return async (...args) => {
const shouldBypassCache = await opts.shouldBypassCache?.(...args);
if (shouldBypassCache) {
return fn(...args);
}
const key = await (opts.getKey || getKey)(...args);
const shouldInvalidateCache = await opts.shouldInvalidateCache?.(...args);
const entry = await get(
key,
() => fn(...args),
shouldInvalidateCache,
args[0] && isEvent(args[0]) ? args[0] : void 0
);
let value = entry.value;
if (opts.transform) {
value = await opts.transform(entry, ...args) || value;
}
return value;
};
}
function cachedFunction(fn, opts = {}) {
return defineCachedFunction(fn, opts);
}
function getKey(...args) {
return args.length > 0 ? hash(args) : "";
}
function escapeKey(key) {
return String(key).replace(/\W/g, "");
}
function defineCachedEventHandler(handler, opts = defaultCacheOptions()) {
const variableHeaderNames = (opts.varies || []).filter(Boolean).map((h) => h.toLowerCase()).sort();
const _opts = {
...opts,
getKey: async (event) => {
const customKey = await opts.getKey?.(event);
if (customKey) {
return escapeKey(customKey);
}
const _path = event.node.req.originalUrl || event.node.req.url || event.path;
let _pathname;
try {
_pathname = escapeKey(decodeURI(parseURL(_path).pathname)).slice(0, 16) || "index";
} catch {
_pathname = "-";
}
const _hashedPath = `${_pathname}.${hash(_path)}`;
const _headers = variableHeaderNames.map((header) => [header, event.node.req.headers[header]]).map(([name, value]) => `${escapeKey(name)}.${hash(value)}`);
return [_hashedPath, ..._headers].join(":");
},
validate: (entry) => {
if (!entry.value) {
return false;
}
if (entry.value.code >= 400) {
return false;
}
if (entry.value.body === void 0) {
return false;
}
if (entry.value.headers.etag === "undefined" || entry.value.headers["last-modified"] === "undefined") {
return false;
}
return true;
},
group: opts.group || "nitro/handlers",
integrity: opts.integrity || hash([handler, opts])
};
const _cachedHandler = cachedFunction(
async (incomingEvent) => {
const variableHeaders = {};
for (const header of variableHeaderNames) {
const value = incomingEvent.node.req.headers[header];
if (value !== void 0) {
variableHeaders[header] = value;
}
}
const reqProxy = cloneWithProxy(incomingEvent.node.req, {
headers: variableHeaders
});
const resHeaders = {};
let _resSendBody;
const resProxy = cloneWithProxy(incomingEvent.node.res, {
statusCode: 200,
writableEnded: false,
writableFinished: false,
headersSent: false,
closed: false,
getHeader(name) {
return resHeaders[name];
},
setHeader(name, value) {
resHeaders[name] = value;
return this;
},
getHeaderNames() {
return Object.keys(resHeaders);
},
hasHeader(name) {
return name in resHeaders;
},
removeHeader(name) {
delete resHeaders[name];
},
getHeaders() {
return resHeaders;
},
end(chunk, arg2, arg3) {
if (typeof chunk === "string") {
_resSendBody = chunk;
}
if (typeof arg2 === "function") {
arg2();
}
if (typeof arg3 === "function") {
arg3();
}
return this;
},
write(chunk, arg2, arg3) {
if (typeof chunk === "string") {
_resSendBody = chunk;
}
if (typeof arg2 === "function") {
arg2(void 0);
}
if (typeof arg3 === "function") {
arg3();
}
return true;
},
writeHead(statusCode, headers2) {
this.statusCode = statusCode;
if (headers2) {
if (Array.isArray(headers2) || typeof headers2 === "string") {
throw new TypeError("Raw headers is not supported.");
}
for (const header in headers2) {
const value = headers2[header];
if (value !== void 0) {
this.setHeader(
header,
value
);
}
}
}
return this;
}
});
const event = createEvent(reqProxy, resProxy);
event.fetch = (url, fetchOptions) => fetchWithEvent(event, url, fetchOptions, {
fetch: useNitroApp().localFetch
});
event.$fetch = (url, fetchOptions) => fetchWithEvent(event, url, fetchOptions, {
fetch: globalThis.$fetch
});
event.waitUntil = incomingEvent.waitUntil;
event.context = incomingEvent.context;
event.context.cache = {
options: _opts
};
const body = await handler(event) || _resSendBody;
const headers = event.node.res.getHeaders();
headers.etag = String(
headers.Etag || headers.etag || `W/"${hash(body)}"`
);
headers["last-modified"] = String(
headers["Last-Modified"] || headers["last-modified"] || (/* @__PURE__ */ new Date()).toUTCString()
);
const cacheControl = [];
if (opts.swr) {
if (opts.maxAge) {
cacheControl.push(`s-maxage=${opts.maxAge}`);
}
if (opts.staleMaxAge) {
cacheControl.push(`stale-while-revalidate=${opts.staleMaxAge}`);
} else {
cacheControl.push("stale-while-revalidate");
}
} else if (opts.maxAge) {
cacheControl.push(`max-age=${opts.maxAge}`);
}
if (cacheControl.length > 0) {
headers["cache-control"] = cacheControl.join(", ");
}
const cacheEntry = {
code: event.node.res.statusCode,
headers,
body
};
return cacheEntry;
},
_opts
);
return defineEventHandler(async (event) => {
if (opts.headersOnly) {
if (handleCacheHeaders(event, { maxAge: opts.maxAge })) {
return;
}
return handler(event);
}
const response = await _cachedHandler(
event
);
if (event.node.res.headersSent || event.node.res.writableEnded) {
return response.body;
}
if (handleCacheHeaders(event, {
modifiedTime: new Date(response.headers["last-modified"]),
etag: response.headers.etag,
maxAge: opts.maxAge
})) {
return;
}
event.node.res.statusCode = response.code;
for (const name in response.headers) {
const value = response.headers[name];
if (name === "set-cookie") {
event.node.res.appendHeader(
name,
splitCookiesString(value)
);
} else {
if (value !== void 0) {
event.node.res.setHeader(name, value);
}
}
}
return response.body;
});
}
function cloneWithProxy(obj, overrides) {
return new Proxy(obj, {
get(target, property, receiver) {
if (property in overrides) {
return overrides[property];
}
return Reflect.get(target, property, receiver);
},
set(target, property, value, receiver) {
if (property in overrides) {
overrides[property] = value;
return true;
}
return Reflect.set(target, property, value, receiver);
}
});
}
const cachedEventHandler = defineCachedEventHandler;
function klona(x) {
if (typeof x !== 'object') return x;
var k, tmp, str=Object.prototype.toString.call(x);
if (str === '[object Object]') {
if (x.constructor !== Object && typeof x.constructor === 'function') {
tmp = new x.constructor();
for (k in x) {
if (x.hasOwnProperty(k) && tmp[k] !== x[k]) {
tmp[k] = klona(x[k]);
}
}
} else {
tmp = {}; // null
for (k in x) {
if (k === '__proto__') {
Object.defineProperty(tmp, k, {
value: klona(x[k]),
configurable: true,
enumerable: true,
writable: true,
});
} else {
tmp[k] = klona(x[k]);
}
}
}
return tmp;
}
if (str === '[object Array]') {
k = x.length;
for (tmp=Array(k); k--;) {
tmp[k] = klona(x[k]);
}
return tmp;
}
if (str === '[object Set]') {
tmp = new Set;
x.forEach(function (val) {
tmp.add(klona(val));
});
return tmp;
}
if (str === '[object Map]') {
tmp = new Map;
x.forEach(function (val, key) {
tmp.set(klona(key), klona(val));
});
return tmp;
}
if (str === '[object Date]') {
return new Date(+x);
}
if (str === '[object RegExp]') {
tmp = new RegExp(x.source, x.flags);
tmp.lastIndex = x.lastIndex;
return tmp;
}
if (str === '[object DataView]') {
return new x.constructor( klona(x.buffer) );
}
if (str === '[object ArrayBuffer]') {
return x.slice(0);
}
// ArrayBuffer.isView(x)
// ~> `new` bcuz `Buffer.slice` => ref
if (str.slice(-6) === 'Array]') {
return new x.constructor(x);
}
return x;
}
const inlineAppConfig = {
"nuxt": {}
};
const appConfig = defuFn(inlineAppConfig);
const NUMBER_CHAR_RE = /\d/;
const STR_SPLITTERS = ["-", "_", "/", "."];
function isUppercase(char = "") {
if (NUMBER_CHAR_RE.test(char)) {
return void 0;
}
return char !== char.toLowerCase();
}
function splitByCase(str, separators) {
const splitters = STR_SPLITTERS;
const parts = [];
if (!str || typeof str !== "string") {
return parts;
}
let buff = "";
let previousUpper;
let previousSplitter;
for (const char of str) {
const isSplitter = splitters.includes(char);
if (isSplitter === true) {
parts.push(buff);
buff = "";
previousUpper = void 0;
continue;
}
const isUpper = isUppercase(char);
if (previousSplitter === false) {
if (previousUpper === false && isUpper === true) {
parts.push(buff);
buff = char;
previousUpper = isUpper;
continue;
}
if (previousUpper === true && isUpper === false && buff.length > 1) {
const lastChar = buff.at(-1);
parts.push(buff.slice(0, Math.max(0, buff.length - 1)));
buff = lastChar + char;
previousUpper = isUpper;
continue;
}
}
buff += char;
previousUpper = isUpper;
previousSplitter = isSplitter;
}
parts.push(buff);
return parts;
}
function kebabCase(str, joiner) {
return str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => p.toLowerCase()).join(joiner) : "";
}
function snakeCase(str) {
return kebabCase(str || "", "_");
}
function getEnv(key, opts) {
const envKey = snakeCase(key).toUpperCase();
return destr(
process.env[opts.prefix + envKey] ?? process.env[opts.altPrefix + envKey]
);
}
function _isObject(input) {
return typeof input === "object" && !Array.isArray(input);
}
function applyEnv(obj, opts, parentKey = "") {
for (const key in obj) {
const subKey = parentKey ? `${parentKey}_${key}` : key;
const envValue = getEnv(subKey, opts);
if (_isObject(obj[key])) {
if (_isObject(envValue)) {
obj[key] = { ...obj[key], ...envValue };
applyEnv(obj[key], opts, subKey);
} else if (envValue === void 0) {
applyEnv(obj[key], opts, subKey);
} else {
obj[key] = envValue ?? obj[key];
}
} else {
obj[key] = envValue ?? obj[key];
}
if (opts.envExpansion && typeof obj[key] === "string") {
obj[key] = _expandFromEnv(obj[key]);
}
}
return obj;
}
const envExpandRx = /\{\{([^{}]*)\}\}/g;
function _expandFromEnv(value) {
return value.replace(envExpandRx, (match, key) => {
return process.env[key] || match;
});
}
const _inlineRuntimeConfig = {
"app": {
"baseURL": "/",
"buildId": "f5b6ccee-0c83-43d5-86e7-8dae6c4b4232",
"buildAssetsDir": "/_nuxt/",
"cdnURL": ""
},
"nitro": {
"envPrefix": "NUXT_",
"routeRules": {
"/__nuxt_error": {
"cache": false
},
"/_nuxt/builds/meta/**": {
"headers": {
"cache-control": "public, max-age=31536000, immutable"
}
},
"/_nuxt/builds/**": {
"headers": {
"cache-control": "public, max-age=1, immutable"
}
},
"/_nuxt/**": {
"headers": {
"cache-control": "public, max-age=31536000, immutable"
}
}
}
},
"public": {
"i18n": {
"baseUrl": "",
"defaultLocale": "hu",
"rootRedirect": "",
"redirectStatusCode": 302,
"skipSettingLocaleOnNavigate": false,
"locales": [
{
"code": "hu",
"iso": "hu-HU",
"name": "Magyar",
"language": ""
},
{
"code": "en",
"iso": "en-GB",
"name": "English",
"language": ""
}
],
"detectBrowserLanguage": {
"alwaysRedirect": false,
"cookieCrossOrigin": false,
"cookieDomain": "",
"cookieKey": "i18n_redirected",
"cookieSecure": false,
"fallbackLocale": "",
"redirectOn": "root",
"useCookie": true
},
"experimental": {
"localeDetector": "",
"typedPages": true,
"typedOptionsAndMessages": false,
"alternateLinkCanonicalQueries": true,
"devCache": false,
"cacheLifetime": "",
"stripMessagesPayload": false,
"preload": false,
"strictSeo": false,
"nitroContextDetection": true,
"httpCacheDuration": 10,
"compactRoutes": false,
"prerenderMessages": false
},
"domainLocales": {
"hu": {
"domain": ""
},
"en": {
"domain": ""
}
}
}
}
};
const envOptions = {
prefix: "NITRO_",
altPrefix: _inlineRuntimeConfig.nitro.envPrefix ?? process.env.NITRO_ENV_PREFIX ?? "_",
envExpansion: _inlineRuntimeConfig.nitro.envExpansion ?? process.env.NITRO_ENV_EXPANSION ?? false
};
const _sharedRuntimeConfig = _deepFreeze(
applyEnv(klona(_inlineRuntimeConfig), envOptions)
);
function useRuntimeConfig(event) {
if (!event) {
return _sharedRuntimeConfig;
}
if (event.context.nitro.runtimeConfig) {
return event.context.nitro.runtimeConfig;
}
const runtimeConfig = klona(_inlineRuntimeConfig);
applyEnv(runtimeConfig, envOptions);
event.context.nitro.runtimeConfig = runtimeConfig;
return runtimeConfig;
}
_deepFreeze(klona(appConfig));
function _deepFreeze(object) {
const propNames = Object.getOwnPropertyNames(object);
for (const name of propNames) {
const value = object[name];
if (value && typeof value === "object") {
_deepFreeze(value);
}
}
return Object.freeze(object);
}
new Proxy(/* @__PURE__ */ Object.create(null), {
get: (_, prop) => {
console.warn(
"Please use `useRuntimeConfig()` instead of accessing config directly."
);
const runtimeConfig = useRuntimeConfig();
if (prop in runtimeConfig) {
return runtimeConfig[prop];
}
return void 0;
}
});
function createContext(opts = {}) {
let currentInstance;
let isSingleton = false;
const checkConflict = (instance) => {
if (currentInstance && currentInstance !== instance) {
throw new Error("Context conflict");
}
};
let als;
if (opts.asyncContext) {
const _AsyncLocalStorage = opts.AsyncLocalStorage || globalThis.AsyncLocalStorage;
if (_AsyncLocalStorage) {
als = new _AsyncLocalStorage();
} else {
console.warn("[unctx] `AsyncLocalStorage` is not provided.");
}
}
const _getCurrentInstance = () => {
if (als) {
const instance = als.getStore();
if (instance !== void 0) {
return instance;
}
}
return currentInstance;
};
return {
use: () => {
const _instance = _getCurrentInstance();
if (_instance === void 0) {
throw new Error("Context is not available");
}
return _instance;
},
tryUse: () => {
return _getCurrentInstance();
},
set: (instance, replace) => {
if (!replace) {
checkConflict(instance);
}
currentInstance = instance;
isSingleton = true;
},
unset: () => {
currentInstance = void 0;
isSingleton = false;
},
call: (instance, callback) => {
checkConflict(instance);
currentInstance = instance;
try {
return als ? als.run(instance, callback) : callback();
} finally {
if (!isSingleton) {
currentInstance = void 0;
}
}
},
async callAsync(instance, callback) {
currentInstance = instance;
const onRestore = () => {
currentInstance = instance;
};
const onLeave = () => currentInstance === instance ? onRestore : void 0;
asyncHandlers.add(onLeave);
try {
const r = als ? als.run(instance, callback) : callback();
if (!isSingleton) {
currentInstance = void 0;
}
return await r;
} finally {
asyncHandlers.delete(onLeave);
}
}
};
}
function createNamespace(defaultOpts = {}) {
const contexts = {};
return {
get(key, opts = {}) {
if (!contexts[key]) {
contexts[key] = createContext({ ...defaultOpts, ...opts });
}
return contexts[key];
}
};
}
const _globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : {};
const globalKey = "__unctx__";
const defaultNamespace = _globalThis[globalKey] || (_globalThis[globalKey] = createNamespace());
const getContext = (key, opts = {}) => defaultNamespace.get(key, opts);
const asyncHandlersKey = "__unctx_async_handlers__";
const asyncHandlers = _globalThis[asyncHandlersKey] || (_globalThis[asyncHandlersKey] = /* @__PURE__ */ new Set());
function executeAsync(function_) {
const restores = [];
for (const leaveHandler of asyncHandlers) {
const restore2 = leaveHandler();
if (restore2) {
restores.push(restore2);
}
}
const restore = () => {
for (const restore2 of restores) {
restore2();
}
};
let awaitable = function_();
if (awaitable && typeof awaitable === "object" && "catch" in awaitable) {
awaitable = awaitable.catch((error) => {
restore();
throw error;
});
}
return [awaitable, restore];
}
getContext("nitro-app", {
asyncContext: false,
AsyncLocalStorage: void 0
});
function isPathInScope(pathname, base) {
let canonical;
try {
const pre = pathname.replace(/%2f/gi, "/").replace(/%5c/gi, "\\");
canonical = new URL(pre, "http://_").pathname;
} catch {
return false;
}
return !base || canonical === base || canonical.startsWith(base + "/");
}
const config = useRuntimeConfig();
const _routeRulesMatcher = toRouteMatcher(
createRouter$1({ routes: config.nitro.routeRules })
);
function createRouteRulesHandler(ctx) {
return eventHandler((event) => {
const routeRules = getRouteRules(event);
if (routeRules.headers) {
setHeaders(event, routeRules.headers);
}
if (routeRules.redirect) {
let target = routeRules.redirect.to;
if (target.endsWith("/**")) {
let targetPath = event.path;
const strpBase = routeRules.redirect._redirectStripBase;
if (strpBase) {
if (!isPathInScope(event.path.split("?")[0], strpBase)) {
throw createError$1({ statusCode: 400 });
}
targetPath = withoutBase(targetPath, strpBase);
} else if (targetPath.startsWith("//")) {
targetPath = targetPath.replace(/^\/+/, "/");
}
target = joinURL(target.slice(0, -3), targetPath);
} else if (event.path.includes("?")) {
const query = getQuery$1(event.path);
target = withQuery(target, query);
}
return sendRedirect(event, target, routeRules.redirect.statusCode);
}
if (routeRules.proxy) {
let target = routeRules.proxy.to;
if (target.endsWith("/**")) {
let targetPath = event.path;
const strpBase = routeRules.proxy._proxyStripBase;
if (strpBase) {
if (!isPathInScope(event.path.split("?")[0], strpBase)) {
throw createError$1({ statusCode: 400 });
}
targetPath = withoutBase(targetPath, strpBase);
} else if (targetPath.startsWith("//")) {
targetPath = targetPath.replace(/^\/+/, "/");
}
target = joinURL(target.slice(0, -3), targetPath);
} else if (event.path.includes("?")) {
const query = getQuery$1(event.path);
target = withQuery(target, query);
}
return proxyRequest(event, target, {
fetch: ctx.localFetch,
...routeRules.proxy
});
}
});
}
function getRouteRules(event) {
event.context._nitro = event.context._nitro || {};
if (!event.context._nitro.routeRules) {
event.context._nitro.routeRules = getRouteRulesForPath(
withoutBase(event.path.split("?")[0], useRuntimeConfig().app.baseURL)
);
}
return event.context._nitro.routeRules;
}
function getRouteRulesForPath(path) {
return defu({}, ..._routeRulesMatcher.matchAll(path).reverse());
}
function _captureError(error, type) {
console.error(`[${type}]`, error);
useNitroApp().captureError(error, { tags: [type] });
}
function trapUnhandledNodeErrors() {
process.on(
"unhandledRejection",
(error) => _captureError(error, "unhandledRejection")
);
process.on(
"uncaughtException",
(error) => _captureError(error, "uncaughtException")
);
}
function joinHeaders(value) {
return Array.isArray(value) ? value.join(", ") : String(value);
}
function normalizeFetchResponse(response) {
if (!response.headers.has("set-cookie")) {
return response;
}
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: normalizeCookieHeaders(response.headers)
});
}
function normalizeCookieHeader(header = "") {
return splitCookiesString(joinHeaders(header));
}
function normalizeCookieHeaders(headers) {
const outgoingHeaders = new Headers();
for (const [name, header] of headers) {
if (name === "set-cookie") {
for (const cookie of normalizeCookieHeader(header)) {
outgoingHeaders.append("set-cookie", cookie);
}
} else {
outgoingHeaders.set(name, joinHeaders(header));
}
}
return outgoingHeaders;
}
function isJsonRequest(event) {
if (hasReqHeader(event, "accept", "text/html")) {
return false;
}
return hasReqHeader(event, "accept", "application/json") || hasReqHeader(event, "user-agent", "curl/") || hasReqHeader(event, "user-agent", "httpie/") || hasReqHeader(event, "sec-fetch-mode", "cors") || event.path.startsWith("/api/") || event.path.endsWith(".json");
}
function hasReqHeader(event, name, includes) {
const value = getRequestHeader(event, name);
return !!(value && typeof value === "string" && value.toLowerCase().includes(includes));
}
const errorHandler$0 = (async function errorhandler(error, event, { defaultHandler }) {
if (event.handled || isJsonRequest(event)) {
return;
}
const defaultRes = await defaultHandler(error, event, { json: true });
const status = error.status || error.statusCode || 500;
if (status === 404 && defaultRes.status === 302) {
setResponseHeaders(event, defaultRes.headers);
setResponseStatus(event, defaultRes.status, defaultRes.statusText);
return send(event, JSON.stringify(defaultRes.body, null, 2));
}
const errorObject = defaultRes.body;
const url = new URL(errorObject.url);
errorObject.url = withoutBase(url.pathname, useRuntimeConfig(event).app.baseURL) + url.search + url.hash;
errorObject.message = error.unhandled ? errorObject.message || "Server Error" : error.message || errorObject.message || "Server Error";
errorObject.data ||= error.data;
errorObject.statusText ||= error.statusText || error.statusMessage;
delete defaultRes.headers["content-type"];
delete defaultRes.headers["content-security-policy"];
setResponseHeaders(event, defaultRes.headers);
const reqHeaders = getRequestHeaders(event);
const isRenderingError = event.path.startsWith("/__nuxt_error") || !!reqHeaders["x-nuxt-error"] || !!event.context.nuxt?.["~rendering-error"];
if (!isRenderingError) {
event.context.nuxt ||= {};
event.context.nuxt["~rendering-error"] = true;
}
const res = isRenderingError ? null : await useNitroApp().localFetch(withQuery(joinURL(useRuntimeConfig(event).app.baseURL, "/__nuxt_error"), errorObject), {
headers: {
...reqHeaders,
"x-nuxt-error": "true"
},
redirect: "manual"
}).catch(() => null);
if (event.handled) {
return;
}
if (!res) {
const { template } = await import('../_/error-500.mjs');
setResponseHeader(event, "Content-Type", "text/html;charset=UTF-8");
return send(event, template(errorObject));
}
const html = await res.text();
for (const [header, value] of res.headers.entries()) {
if (header === "set-cookie") {
appendResponseHeader(event, header, value);
continue;
}
setResponseHeader(event, header, value);
}
setResponseStatus(event, res.status && res.status !== 200 ? res.status : defaultRes.status, res.statusText || defaultRes.statusText);
return send(event, html);
});
function defineNitroErrorHandler(handler) {
return handler;
}
const errorHandler$1 = defineNitroErrorHandler(
function defaultNitroErrorHandler(error, event) {
const res = defaultHandler(error, event);
setResponseHeaders(event, res.headers);
setResponseStatus(event, res.status, res.statusText);
return send(event, JSON.stringify(res.body, null, 2));
}
);
function defaultHandler(error, event, opts) {
const isSensitive = error.unhandled || error.fatal;
const statusCode = error.statusCode || 500;
const statusMessage = error.statusMessage || "Server Error";
const url = getRequestURL(event, { xForwardedHost: true, xForwardedProto: true });
if (statusCode === 404) {
const baseURL = "/";
if (/^\/[^/]/.test(baseURL) && !url.pathname.startsWith(baseURL)) {
const redirectTo = `${baseURL}${url.pathname.slice(1)}${url.search}`;
return {
status: 302,
statusText: "Found",
headers: { location: redirectTo },
body: `Redirecting...`
};
}
}
if (isSensitive && !opts?.silent) {
const tags = [error.unhandled && "[unhandled]", error.fatal && "[fatal]"].filter(Boolean).join(" ");
console.error(`[request error] ${tags} [${event.method}] ${url}
`, error);
}
const headers = {
"content-type": "application/json",
// Prevent browser from guessing the MIME types of resources.
"x-content-type-options": "nosniff",
// Prevent error page from being embedded in an iframe
"x-frame-options": "DENY",
// Prevent browsers from sending the Referer header
"referrer-policy": "no-referrer",
// Disable the execution of any js
"content-security-policy": "script-src 'none'; frame-ancestors 'none';"
};
setResponseStatus(event, statusCode, statusMessage);
if (statusCode === 404 || !getResponseHeader(event, "cache-control")) {
headers["cache-control"] = "no-cache";
}
const body = {
error: true,
url: url.href,
statusCode,
statusMessage,
message: isSensitive ? "Server Error" : error.message,
data: isSensitive ? void 0 : error.data
};
return {
status: statusCode,
statusText: statusMessage,
headers,
body
};
}
const errorHandlers = [errorHandler$0, errorHandler$1];
async function errorHandler(error, event) {
for (const handler of errorHandlers) {
try {
await handler(error, event, { defaultHandler });
if (event.handled) {
return; // Response handled
}
} catch(error) {
// Handler itself thrown, log and continue
console.error(error);
}
}
// H3 will handle fallback
}
/*!
* shared v11.4.2
* (c) 2026 kazuya kawaguchi
* Released under the MIT License.
*/
const _create = Object.create;
const create = (obj = null) => _create(obj);
/* eslint-enable */
/**
* Useful Utilities By Evan you
* Modified by kazuya kawaguchi
* MIT License
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
*/
const isArray = Array.isArray;
const isFunction = (val) => typeof val === 'function';
const isString = (val) => typeof val === 'string';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isObject = (val) => val !== null && typeof val === 'object';
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function deepCopy(src, des) {
// src and des should both be objects, and none of them can be a array
if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
throw new Error('Invalid value');
}
const stack = [{ src, des }];
while (stack.length) {
const { src, des } = stack.pop();
// using `Object.keys` which skips prototype properties
Object.keys(src).forEach(key => {
if (key === '__proto__') {
return;
}
// if src[key] is an object/array, set des[key]
// to empty object/array to prevent setting by reference
if (isObject(src[key]) && !isObject(des[key])) {
des[key] = Array.isArray(src[key]) ? [] : create();
}
if (isNotObjectOrIsArray(des[key]) || isNotObjectOrIsArray(src[key])) {
// replace with src[key] when:
// src[key] or des[key] is not an object, or
// src[key] or des[key] is an array
des[key] = src[key];
}
else {
// src[key] and des[key] are both objects, merge them
stack.push({ src: src[key], des: des[key] });
}
});
}
}
const __nuxtMock = { runWithContext: async (fn) => await fn() };
const merger = createDefu((obj, key, value) => {
if (key === "messages" || key === "datetimeFormats" || key === "numberFormats") {
obj[key] ??= create(null);
deepCopy(value, obj[key]);
return true;
}
});
async function loadVueI18nOptions(vueI18nConfigs) {
const nuxtApp = __nuxtMock;
let vueI18nOptions = { messages: create(null) };
for (const configFile of vueI18nConfigs) {
const resolver = await configFile().then((x) => isModule(x) ? x.default : x);
const resolved = isFunction(resolver) ? await nuxtApp.runWithContext(() => resolver()) : resolver;
vueI18nOptions = merger(create(null), resolved, vueI18nOptions);
}
vueI18nOptions.fallbackLocale ??= false;
return vueI18nOptions;
}
const isModule = (val) => toTypeString(val) === "[object Module]";
async function getLocaleMessages(locale, loader) {
const nuxtApp = __nuxtMock;
try {
const getter = await nuxtApp.runWithContext(loader.load).then((x) => isModule(x) ? x.default : x);
return isFunction(getter) ? await nuxtApp.runWithContext(() => getter(locale)) : getter;
} catch (e) {
throw new Error(`Failed loading locale (${locale}): ` + e.message);
}
}
async function getLocaleMessagesMerged(locale, loaders = []) {
const nuxtApp = __nuxtMock;
const messages = await Promise.all(
loaders.map((loader) => nuxtApp.runWithContext(() => getLocaleMessages(locale, loader)))
);
const merged = {};
for (const message of messages) {
deepCopy(message, merged);
}
return merged;
}
var permissions$1 = {
title: "Jogosultság Kezelés",
subtitle: "Jogosultsági Mátrix — Szerepkör alapú hozzáférés-vezérlés",
loading: "Jogosultságok betöltése...",
error_title: "Nem sikerült betölteni a jogosultságokat",
retry: "Újra",
save_changes: "Változtatások Mentése",
discard: "Elvetés",
modified_count: "{count} módosítás",
domain_filter: "Tartomány Szűrő (Sorok)",
role_filter: "Szerepkör Szűrő (Oszlopok)",
select_all: "Összes kiválasztása",
deselect_all: "Összes elrejtése",
all_domains: "Minden",
permission: "Engedély",
no_permissions: "Nincsenek engedélyek ebben a tartományban.",
current_tier: "Aktuális Csomag",
expires: "Lejárat",
superadmin: "Superadmin",
superadmin_desc: "Teljes rendszer hozzáférés — felhasználók, számlázás, robotok és rendszerkonfiguráció.",
garages: "Garázsok",
garages_desc: "Garázs szintű hozzáférés — járműkezelés, szervizfoglalás, ügyféladatok.",
feature_flags: "Feature Flags",
feature_flags_desc: "Előfizetési funkciók — a jelenlegi csomagod alapján ({tier}).",
rbac_title: "RBAC Jogosultsági Mátrix",
rbac_desc: "Szerepkör alapú hozzáférés-vezérlés — mely szerepkörök mely admin műveleteket végezhetik.",
action: "Művelet"
};
var packages$1 = {
title: "Csomagok Kezelése",
subtitle: "Előfizetési csomagok és funkciók kezelése — Free, Premium, Enterprise",
loading: "Csomagok betöltése...",
retry: "Újra",
create_new: "Új Csomag",
no_packages: "Még nincsenek csomagok",
no_packages_desc: "Hozd létre az első előfizetési csomagot a kezdéshez.",
create_first: "Első Csomag Létrehozása",
popular: "Népszerű",
fallback_badge: "Visszaesési",
trial_badge: "Próba",
month: "hó",
feature_flags: "Elérhető Funkciók",
edit: "Szerkesztés",
duplicate: "Másolás",
"delete": "Törlés",
set_as_default: "Beállítás alapértelmezettként",
set_as_default_success: "alapértelmezett csomagként beállítva!",
edit_title: "Csomag Szerkesztése",
create_title: "Csomag Létrehozása",
cancel: "Mégse",
save: "Változtatások Mentése",
create: "Létrehozás",
save_success: "Csomag sikeresen frissítve!",
delete_title: "Csomag Törlése",
delete_confirm: "Biztosan törölni szeretnéd a \"{name}\" csomagot?",
delete_btn: "Törlés",
allowances: "Korlátok",
max_vehicles: "Max Jármű",
max_garages: "Max Garázs",
max_users: "Max Dolgozó",
monthly_credits: "Havi Kredit",
tier_level: "Szint",
form_name: "Rendszer Név",
form_name_placeholder: "pl. premium_2024",
form_display_name: "Megjelenítési Név",
form_display_name_placeholder: "pl. Premium Plus",
form_type: "Típus",
type_private: "Magán",
type_corporate: "Vállalati",
form_tier_level: "Szintszám",
form_tier_level_hint: "Magasabb szám = több funkció és magasabb rang",
form_monthly_price: "Havi Díj",
form_yearly_price: "Éves Díj",
form_currency: "Pénznem",
form_subtitle: "Felirat / Leírás",
form_subtitle_placeholder: "pl. Ideális kisvállalkozásoknak",
form_badge: "Jelvény Szöveg",
form_badge_placeholder: "pl. Legnépszerűbb",
form_is_custom: "Egyedi Csomag (nem publikus)",
singleton_rules: "Egyediségi Szabályok",
form_is_default_fallback: "Alapértelmezett Visszaesési Csomag — lejárt előfizetés esetén erre vált",
form_trial_days: "Próba Napok Regisztrációnál",
form_trial_days_hint: "Az új szervezetek ennyi ingyenes napot kapnak. Csak egy csomagnál lehet > 0.",
per_region_pricing: "Régiók szerinti árazás",
smart_calculator: "Okos Árkalkulátor",
calc_net_price: "Nettó ár",
calc_vat_rate: "ÁFA kulcs",
calc_currency: "Pénznem",
calc_net: "Nettó",
calc_vat: "ÁFA",
calc_gross: "Bruttó",
calc_apply: "Alkalmaz a kiválasztott régióra",
add_zone: "Új Zóna Hozzáadása",
add_zone_select: "Válassz országkódot...",
add_zone_already_exists: "Ez a régió már létezik a csomag árazásában!"
};
var garages$1 = {
title: "Garázsok CRM",
subtitle: "Garázsok listája, csomagkezelés és státuszmódosítás",
total_garages: "Összes Garázs",
private_garages: "Privát Garázsok",
corporate_garages: "Céges Garázsok",
search_placeholder: "Keresés név, kapcsolattartó vagy e-mail alapján...",
all_tiers: "Összes csomag",
all_types: "Összes típus",
type_individual: "Privát (Egyéni)",
type_corporate: "Céges (Vállalati)",
company_name: "Cégnév",
email: "E-mail",
status: "Státusz",
current_package: "Aktuális Csomag",
expiration_date: "Lejárat Dátuma",
actions: "Műveletek",
active: "Aktív",
inactive: "Inaktív",
suspended: "Felfüggesztve",
change_package: "Csomag Módosítása",
manage_subscription: "Előfizetés Kezelése",
view: "Megtekintés",
activate: "Aktiválás",
deactivate: "Deaktiválás",
no_results: "Nincs a keresésnek megfelelő garázs.",
loading: "Garázsok betöltése...",
retry: "Újra",
members: "tag",
free_fallback: "Ingyenes / Visszaesési",
expires: "Lejárat",
select_package: "Csomag Kiválasztása",
select_package_placeholder: "Válassz egy előfizetési csomagot...",
custom_expiration: "Egyéni Lejárati Dátum",
optional: "opcionális",
custom_expiration_hint: "Hagyd üresen az alapértelmezett időtartamhoz (pl. 30 nap). 2-5 éves B2B deal-eknél adj meg egyedi dátumot!",
cancel: "Mégse",
save: "Mentés",
saving: "Mentés...",
subscription_updated: "előfizetése sikeresen frissítve!",
view_details: "Részletek",
indefinite: "Határozatlan",
addons_title: "Kiegészítők (Add-ons)",
addon_vehicles: "Extra Jármű",
addon_branches: "Extra Telephely",
addon_users: "Extra Dolgozó",
active_addons: "Aktív kiegészítők",
no_active_addons: "Nincsenek aktív kiegészítők",
addon_vehicles_expiration: "Extra Jármű lejárati dátuma",
addon_branches_expiration: "Extra Telephely lejárati dátuma",
addon_users_expiration: "Extra Dolgozó lejárati dátuma",
addon_expiration_hint: "Ha üres, a meglévő lejárati dátumok megmaradnak.",
details: {
loading: "Garázs adatainak betöltése...",
retry: "Újra",
back: "Vissza a garázsokhoz",
company_info: "Cég adatok",
company_name: "Cégnév",
display_name: "Megjelenítési név",
org_type: "Szervezet típusa",
tax_number: "Adószám",
reg_number: "Cégjegyzékszám",
created_at: "Létrehozva",
address: "Cím",
subscription_info: "Előfizetés státusza",
tier_name: "Csomag",
tier_level: "Szint",
level_n: "{n}. szint",
expires_at: "Lejárat",
asset_limit: "Járműkorlát",
vehicles: "jármű",
no_subscription: "Nincs aktív előfizetés",
contact_info: "Elérhetőség",
contact_name: "Kapcsolattartó neve",
contact_role: "Szerepkör",
contact_department: "Osztály",
contact_phone: "Kapcsolattartó telefon",
no_contact: "Nincs elsődleges kapcsolattartó",
edit_details: "Adatok Szerkesztése",
save: "Mentés",
generalTab: "Általános",
employeesTab: "Dolgozók",
fleetTab: "Flotta",
analyticsTab: "Analitika",
subscriptionTab: "Előfizetés",
editBasicTab: "Alapadatok",
editContactTab: "Kapcsolat",
editAddressTab: "Címek",
zip: "Irányítószám",
city: "Város",
street_name: "Utca",
street_type: "Utca típusa",
house_number: "Házszám",
coming_soon: "Ez a funkció hamarosan elérhető lesz...",
missing_data_title: "Hiányzó adatok",
missing_data_desc: "A garázs profilja hiányos. Kérjük, egészítse ki a hiányzó adatokat.",
missing_data_activation_required: "A garázs aktiválásához az alábbi adatok pótlása kötelező:",
missing_tax_number: "Adószám",
missing_billing: "Számlázási cím",
missing_contact_email: "Kapcsolattartó e-mail",
missing_contact_phone: "Kapcsolattartó telefon",
missing_data_count: "{count} mező hiányzik",
contact_person_name: "Kapcsolattartó neve",
contact_email: "Kapcsolattartó e-mail",
billing_address: "Számlázási cím",
billing_zip: "Irányítószám",
billing_city: "Város",
billing_street_name: "Utca",
billing_street_type: "Utca típusa",
billing_house_number: "Házszám",
notification_address: "Értesítési cím",
notification_zip: "Irányítószám",
notification_city: "Város",
notification_street_name: "Utca",
notification_street_type: "Utca típusa",
notification_house_number: "Házszám",
tab_basic: "Alapadatok",
tab_contact: "Kapcsolat",
tab_addresses: "Címek",
basic_info: "Alapadatok",
contact_section: "Kapcsolattartó",
addresses_section: "Címek",
vehicles_used: "Járművek",
branches_used: "Telephelyek",
employees_used: "Dolgozók",
branches: "telephely",
employees: "dolgozó",
status: "Státusz",
subscription_history: "Előfizetési Előzmények",
history_date: "Dátum",
history_package: "Csomag",
history_action: "Művelet",
history_status: "Státusz",
no_subscription_history: "Még nincsenek előfizetési előzmények."
},
analytics: {
ltv: "Élettartam Érték (LTV)",
mrr: "Havi Bevétel (MRR)",
monthly_recurring: "Havi ismétlődő bevétel",
outstanding: "Kintlévőség",
all_settled: "Minden számla rendezve",
earned_credits: "Szerzett Kreditek",
contribution_xp: "Platform építésével gyűjtött XP",
invited_companies: "Meghívott Cégek",
companies_joined: "Cég csatlakozott a meghívásodra",
validated_garages: "Validált Garázsok",
garages_confirmed: "Garázs sikeresen hitelesítve",
utilization: "Kihasználtság",
vehicle_quota: "Jármű Kvóta",
employee_quota: "Alkalmazotti Kvóta",
utilized: "kihasználva",
marketplace_engagement: "Piactér & Aktivitás",
avg_rating: "Átlagos Értékelés",
reviews: "Értékelések",
reviews_count: "értékelés",
last_activity: "Utolsó Aktivitás",
last_login_mock: "2 órája",
services_30d: "Elvégzett Szervizek (30 nap)"
},
employees: {
title: "Dolgozók",
total_count: "Összesen {count} fő",
name: "Név",
email_phone: "E-mail / Telefon",
role: "Szerepkör",
status: "Státusz",
actions: "Műveletek",
edit_role: "Szerepkör szerkesztése",
remove: "Eltávolítás",
no_employees: "Még nincsenek tagok ehhez a garázshoz.",
edit_role_title: "Tag szerepkörének szerkesztése",
editRoleTitle: "Tag szerepkörének szerkesztése",
editRoleFor: "{name} szerepkörének módosítása",
cancel: "Mégse",
save: "Mentés",
saveRole: "Szerepkör mentése",
saving: "Mentés...",
status_active: "Aktív",
status_inactive: "Inaktív",
remove_title: "Tag eltávolítása",
removeTitle: "Tag eltávolítása",
remove_confirm: "Biztosan eltávolítod {name} tagot a garázsból?",
removeConfirm: "Biztosan eltávolítod {name} tagot a garázsból?",
remove_btn: "Eltávolítás",
removing: "Eltávolítás...",
add_employee: "Új dolgozó hozzáadása",
addTitle: "Új dolgozó hozzáadása",
email: "E-mail cím",
emailPlaceholder: "Add meg az e-mail címet...",
roleMember: "Tag",
roleManager: "Menedzser",
roleAdmin: "Admin",
roleOwner: "Tulajdonos",
add: "Hozzáadás",
adding: "Hozzáadás..."
},
fleet: {
title: "Flotta",
total_vehicles: "Összesen {count} jármű",
plate: "Rendszám",
brand: "Márka",
model: "Modell",
brand_model: "Márka & Modell",
year: "Évjárat",
status: "Státusz",
vin: "Alvázszám",
no_vehicles: "Ehhez a garázshoz még nincsenek járművek rendelve.",
no_fleet_access: "Nincs jogosultságod a flotta adatok megtekintéséhez."
}
};
var gamification$1 = {
badges: {
title: "Kitüntetések",
subtitle: "Badge-ek kezelése — CRUD",
loading: "Kitüntetések betöltése...",
error: "Nem sikerült betölteni a kitüntetéseket.",
retry: "Újrapróbálkozás",
create: "Új kitüntetés",
no_items: "Még nincsenek kitüntetések.",
id: "ID",
name: "Név",
description: "Leírás",
icon: "Ikon",
actions: "Műveletek",
edit: "Szerkesztés",
"delete": "Törlés",
cancel: "Mégse",
save: "Mentés",
create_title: "Kitüntetés létrehozása",
edit_title: "Kitüntetés szerkesztése",
name_placeholder: "Kitüntetés neve",
desc_placeholder: "Kitüntetés leírása",
icon_placeholder: "Ikon URL",
icon_hint: "Opcionális. Az ikon URL-je a kitüntetéshez.",
icon_preview: "Ikon előnézet",
create_btn: "Létrehozás",
delete_title: "Kitüntetés törlése",
delete_confirm: "Biztosan törölni szeretnéd ezt a kitüntetést?",
delete_btn: "Törlés",
created: "Kitüntetés létrehozva!",
updated: "Kitüntetés frissítve!",
deleted: "Kitüntetés törölve!",
save_error: "Nem sikerült menteni a kitüntetést.",
delete_error: "Nem sikerült törölni a kitüntetést.",
unknown_error: "Ismeretlen hiba"
},
competitions: {
title: "Versenyek",
subtitle: "Szezonális versenyek kezelése",
loading: "Versenyek betöltése...",
error: "Nem sikerült betölteni a versenyeket.",
retry: "Újrapróbálkozás",
create: "Új Verseny",
no_items: "Még nincsenek versenyek létrehozva.",
create_first: "Első Verseny Létrehozása",
season_filter: "Szezon szűrő:",
all_seasons: "Összes szezon",
active_badge: "(Aktív)",
status_active: "Aktív",
status_draft: "Draft",
status_completed: "Befejezett",
status_cancelled: "Törölt",
view_rules: "Szabályok megtekintése",
edit: "Szerkesztés",
cancel: "Mégse",
save: "Mentés",
create_title: "Verseny létrehozása",
edit_title: "Verseny szerkesztése",
name: "Név",
name_placeholder: "Pl. Q1 Szerviz Beküldő Verseny",
description: "Leírás",
desc_placeholder: "Verseny leírása...",
season: "Szezon",
select_season: "Válassz szezont",
start_date: "Kezdő dátum",
end_date: "Záró dátum",
status: "Státusz",
rules: "Szabályok (JSON)",
rules_placeholder: "type: service_submission, points_multiplier: 1.5",
invalid_json: "Érvénytelen JSON formátum!",
create_btn: "Létrehozás",
season_id_label: "Szezon ID:",
save_error: "Hiba történt a mentés során."
},
config: {
title: "Rendszer Konfig",
subtitle: "Gamification master konfiguráció szerkesztése",
loading: "Konfiguráció betöltése...",
error: "Nem sikerült betölteni a konfigurációt.",
last_save: "Utolsó mentés:",
saving: "Mentés...",
save: "Konfiguráció mentése",
section_xp: "XP Logika",
section_conversion: "Konverziós Logika",
section_penalty: "Büntetési Logika",
section_rewards: "Szint Jutalmak",
calculator: "Hatás Kalkulátor",
calculator_desc: "Állítsd be a paramétereket a becsült hatás megtekintéséhez",
estimated_results: "Becsült Eredmények",
daily_xp: "Napi XP",
xp_for_level: "Szintlépéshez Szükséges XP",
social_to_credit: "Social → Credit",
days_to_level: "Szintlépés Napok Száma",
raw_json: "Nyers JSON Szerkesztő",
apply_json: "JSON Alkalmazása",
updated: "Konfiguráció frissítve!",
save_error: "Hiba történt a mentés során.",
json_applied: "JSON alkalmazva a form mezőkre!",
invalid_json: "Érvénytelen JSON: "
},
dashboard: {
title: "Gamification HQ",
subtitle: "Gamification rendszer áttekintő irányítópultja",
loading: "Dashboard betöltése...",
error: "Nem sikerült betölteni a dashboard adatokat.",
total_users: "Összes Felhasználó",
active_season: "Aktív Szezon",
pending_contributions: "Függő Hozzájárulások",
xp_earned_today: "Ma Szerzett XP",
none: "Nincs",
quick_actions: "Gyors Műveletek",
manage_point_rules: "Pontszabályok kezelése",
manage_badges: "Kitüntetések kezelése",
manage_seasons: "Szezonok kezelése",
recent_ledger: "Legutóbbi Pontnapló Bejegyzések",
no_ledger: "Még nincsenek pontnapló bejegyzések.",
top_5: "Top 5 Ranglista",
full_leaderboard: "Teljes ranglista →",
no_leaderboard: "Még nincsenek ranglista adatok.",
level: "Szint",
xp: "XP",
points: "pont"
},
leaderboard: {
title: "Ranglista",
subtitle: "Gamification ranglista admin nézet",
search: "Keresés",
level: "Szint",
min_xp: "Minimum XP",
sort: "Rendezés",
sort_xp: "XP szerint",
sort_points: "Pontok szerint",
sort_social: "Szociális pontok szerint",
sort_level: "Szint szerint",
filter: "Szűrés",
reset: "Visszaállítás",
descending: "Csökkenő",
ascending: "Növekvő",
user: "felhasználó",
loading: "Ranglista betöltése...",
error: "Nem sikerült betölteni a ranglistát.",
retry: "Újrapróbálkozás",
no_results: "Nincs találat a megadott szűrőkkel.",
no_results_hint: "Próbálj más szűrési feltételeket használni.",
user_col: "Felhasználó",
email: "Email",
xp: "XP",
points: "Pontok",
social: "Szociális",
penalty: "Büntetés",
restriction: "Restrikció",
discoveries: "Felfedezések",
services: "Szolgáltatások",
updated: "Utolsó módosítás",
actions: "Műveletek",
details: "Részletek",
prev: "Előző",
next: "Következő",
page_of: "/ oldal",
restriction_mild: "Enyhe",
restriction_moderate: "Közepes",
restriction_severe: "Súlyos"
},
ledger: {
title: "Pontnapló",
subtitle: "Gamification pontnapló böngészése",
loading: "Pontnapló betöltése...",
error: "Nem sikerült betölteni a pontnaplót.",
user_id: "User ID",
date_from: "Dátumtól",
date_to: "Dátumig",
reason: "Ok",
search: "Keresés",
clear: "Törlés",
csv: "CSV",
no_results: "Nincs találat a megadott szűrőkkel.",
no_results_hint: "Próbálj más szűrési feltételeket használni.",
id: "ID",
user: "User",
points: "Pont",
penalty: "Büntetés",
xp: "XP",
source: "Forrás",
date: "Dátum",
prev: "Előző",
next: "Következő",
of: "/",
showing: "mutatva",
filtered: "(szűrve)",
no_csv_data: "Nincs adat a CSV exportáláshoz.",
csv_downloaded: "CSV letöltés elindítva."
},
levels: {
title: "Szintek",
subtitle: "Szint konfigurációk kezelése — CRUD",
loading: "Szintek betöltése...",
error: "Nem sikerült betölteni a szint konfigurációkat.",
retry: "Újrapróbálkozás",
create: "Új szint",
no_items: "Még nincsenek szint konfigurációk.",
level: "Szint",
rank: "Rang",
min_points: "Min. Pont",
type: "Típus",
actions: "Műveletek",
penalty: "Büntető",
normal: "Normál",
tree_diagram: "Szint Fa Diagram",
no_tree_data: "Nincsenek szintek megjelenítéshez.",
points: "pont",
edit_title: "Szint szerkesztése",
create_title: "Szint létrehozása",
level_number: "Szint Száma",
rank_name: "Rang Neve",
min_points_label: "Minimum Pont",
is_penalty: "Büntető szint",
cancel: "Mégse",
save: "Mentés",
saving: "Mentés...",
updated: "Szint frissítve!",
created: "Szint létrehozva!",
duplicate_level: "Ezzel a szint számmal már létezik konfiguráció.",
save_error: "Hiba történt a mentés során."
},
params: {
title: "Rendszerparaméterek",
subtitle: "Gamification kategóriájú rendszerparaméterek",
loading: "Paraméterek betöltése...",
error: "Nem sikerült betölteni a rendszerparamétereket.",
retry: "Újrapróbálkozás",
no_items: "Nincsenek gamification rendszerparaméterek.",
key: "Kulcs",
value: "Érték",
category: "Kategória",
scope: "Hatósugár",
scope_id: "Scope ID",
actions: "Műveletek",
edit: "Szerkesztés",
edit_title: "Paraméter szerkesztése",
value_label: "Érték",
value_placeholder: "Paraméter értéke (JSON vagy sima szöveg)",
json_detected: "🔹 JSON formátum érzékelve",
text_value: "🔸 Szöveges érték",
cancel: "Mégse",
save: "Mentés",
saving: "Mentés...",
invalid_json: "Érvénytelen JSON formátum: ",
save_error: "Hiba történt a mentés során.",
updated: "frissítve!"
},
point_rules: {
title: "Pontszabályok",
subtitle: "Gamification pontszabályok kezelése — CRUD",
loading: "Pontszabályok betöltése...",
error: "Nem sikerült betölteni a pontszabályokat.",
retry: "Újrapróbálkozás",
create: "Új pontszabály",
no_items: "Még nincsenek pontszabályok. Hozz létre egyet a fenti gombbal!",
id: "ID",
action_key: "Akció Kulcs",
points: "Pont",
description: "Leírás",
status: "Státusz",
actions: "Műveletek",
active: "Aktív",
inactive: "Inaktív",
edit: "Szerkesztés",
"delete": "Törlés (soft-delete)",
edit_title: "Pontszabály szerkesztése",
create_title: "Új pontszabály",
action_key_label: "Akció Kulcs",
action_key_placeholder: "pl. service_submitted",
points_label: "Pontérték",
points_placeholder: "0",
description_label: "Leírás",
description_placeholder: "Rövid leírás a szabályról...",
is_active: "Aktív",
cancel: "Mégse",
save: "Mentés",
saving: "Mentés...",
updated: "Pontszabály frissítve!",
created: "Pontszabály létrehozva!",
deleted: "Pontszabály deaktiválva!",
duplicate_key: "Egy szabály ezzel a kulccsal már létezik.",
save_error: "Nem sikerült menteni a pontszabályt.",
delete_title: "Pontszabály törlése",
delete_confirm: "Biztosan deaktiválod a következő szabályt:",
delete_btn: "Törlés",
deleting: "Törlés..."
},
seasons: {
title: "Szezonok",
subtitle: "Gamification szezonkezelés",
loading: "Szezonok betöltése...",
error: "Nem sikerült betölteni a szezonokat.",
retry: "Újra",
create: "Új Szezon",
no_items: "Még nincsenek szezonok létrehozva.",
create_first: "Első Szezon Létrehozása",
active: "Aktív",
inactive: "Inaktív",
created_at: "Létrehozva:",
activate: "Aktiválás",
edit: "Szerkesztés",
edit_title: "Szezon szerkesztése",
create_title: "Új Szezon",
name: "Név",
name_placeholder: "pl. 2026 Q1 Szezon",
start_date: "Kezdő dátum",
end_date: "Záró dátum",
activate_on_create: "Aktiválás létrehozáskor",
cancel: "Mégse",
save: "Mentés",
create_btn: "Létrehozás",
activate_title: "Szezon aktiválása",
activate_confirm: "Biztosan aktiválni szeretnéd",
activate_warning: "Ez deaktiválja az összes többi szezont.",
activating: "Aktiválás...",
activate_btn: "Aktiválás",
save_error: "Nem sikerült menteni a szezont."
},
users: {
title: "Gamification Felhasználók",
subtitle: "Felhasználói gamification statisztikák kezelése",
loading: "Felhasználók betöltése...",
error: "Nem sikerült betölteni a felhasználói statisztikákat.",
retry: "Újra",
no_results: "Nincsenek megjeleníthető felhasználói statisztikák.",
level: "Szint",
all_levels: "Minden Szint",
level_n: "{n}. szint",
min_xp: "Minimum XP",
max_xp: "Maximum XP",
penalty: "Büntetés",
any: "Bármelyik",
only_penalized: "Csak büntetettek",
only_clean: "Csak tiszták",
filter: "Szűrés",
reset: "Visszaállítás",
count: "felhasználó",
user_id: "Felhasználó ID",
xp: "XP",
points: "Pontok",
restriction: "Korlátozás",
services: "Szolgáltatások",
discoveries: "Felfedezések",
updated: "Utolsó frissítés",
actions: "Műveletek",
details: "Részletek",
prev: "Előző",
next: "Következő",
none: "Nincs",
restriction_mild: "Enyhe",
restriction_moderate: "Mérsékelt",
restriction_severe: "Súlyos"
},
user_detail: {
back: "Vissza a listához",
title: "Felhasználó Gamification Részletei",
id_label: "ID:",
loading: "Felhasználó betöltése...",
error: "Nem sikerült betölteni a felhasználói adatokat.",
retry: "Újra",
not_found: "Felhasználó nem található.",
total_xp: "Összes XP",
level: "Szint",
total_points: "Összes Pont",
social_points: "Szociális Pontok",
penalty_points: "Büntető Pontok",
restriction_level: "Korlátozás Szintje",
penalty_quota: "Büntetési Kvóta",
banned_until: "Kitiltva eddig:",
no: "Nincs",
services: "Szolgáltatások",
discovered_places: "Felfedezett Helyek",
validated_places: "Validált Helyek",
added_providers: "Hozzáadott Szolgáltatók",
penalty_form_title: "Büntetés Kiosztása",
penalty_points_label: "Büntető Pontok",
penalty_reason_label: "Indok",
penalty_reason_placeholder: "Büntetés indoka...",
penalty_submit: "Büntetés Kiosztása",
penalty_submitting: "Küldés...",
penalty_success: "Büntetés sikeresen kiosztva: {amount} pont.",
penalty_error: "Nem sikerült kiosztani a büntetést.",
reward_form_title: "Jutalom Kiosztása",
reward_xp_label: "XP Jutalom",
reward_social_label: "Szociális Pont Jutalom",
reward_reason_label: "Indok",
reward_reason_placeholder: "Jutalom indoka...",
reward_submit: "Jutalom Kiosztása",
reward_submitting: "Küldés...",
reward_success: "Jutalom sikeresen kiosztva: {xp} XP, {social} szociális pont.",
reward_error: "Nem sikerült kiosztani a jutalmat.",
ledger_title: "Pont Napló",
ledger_count: "bejegyzés",
ledger_loading: "Betöltés...",
ledger_empty: "Még nincsenek naplóbejegyzések ehhez a felhasználóhoz.",
ledger_date: "Dátum",
ledger_points: "Pontok",
ledger_penalty: "Büntetés",
ledger_xp: "XP",
ledger_reason: "Indok",
ledger_source: "Forrás"
}
};
const locale_hu_46json_ee06c965 = {
permissions: permissions$1,
packages: packages$1,
garages: garages$1,
gamification: gamification$1
};
var permissions = {
title: "Permissions Management",
subtitle: "Permission Matrix — Role-based access control",
loading: "Loading permissions...",
error_title: "Failed to load permissions",
retry: "Retry",
save_changes: "Save Changes",
discard: "Discard",
modified_count: "{count} changes",
domain_filter: "Domain Filter (Rows)",
role_filter: "Role Filter (Columns)",
select_all: "Select All",
deselect_all: "Deselect All",
all_domains: "All",
permission: "Permission",
no_permissions: "No permissions in this domain.",
current_tier: "Current Package",
expires: "Expires",
superadmin: "Superadmin",
superadmin_desc: "Full system access — users, billing, robots and system configuration.",
garages: "Garages",
garages_desc: "Garage-level access — vehicle management, service booking, customer data.",
feature_flags: "Feature Flags",
feature_flags_desc: "Subscription features — based on your current plan ({tier}).",
rbac_title: "RBAC Permission Matrix",
rbac_desc: "Role-based access control — which roles can perform which admin actions.",
action: "Action"
};
var packages = {
title: "Package Management",
subtitle: "Manage subscription packages and features — Free, Premium, Enterprise",
loading: "Loading packages...",
retry: "Retry",
create_new: "New Package",
no_packages: "No packages yet",
no_packages_desc: "Create your first subscription package to get started.",
create_first: "Create First Package",
popular: "Popular",
fallback_badge: "Fallback",
trial_badge: "Trial",
month: "mo",
feature_flags: "Available Features",
edit: "Edit",
duplicate: "Duplicate",
"delete": "Delete",
set_as_default: "Set as Default",
set_as_default_success: "set as default package!",
edit_title: "Edit Package",
create_title: "Create Package",
cancel: "Cancel",
save: "Save Changes",
create: "Create",
save_success: "Package updated successfully!",
delete_title: "Delete Package",
delete_confirm: "Are you sure you want to delete \"{name}\"?",
delete_btn: "Delete",
allowances: "Allowances",
max_vehicles: "Max Vehicles",
max_garages: "Max Garages",
max_users: "Max Users",
monthly_credits: "Monthly Credits",
tier_level: "Level",
form_name: "System Name",
form_name_placeholder: "e.g. premium_2024",
form_display_name: "Display Name",
form_display_name_placeholder: "e.g. Premium Plus",
form_type: "Type",
type_private: "Private",
type_corporate: "Corporate",
form_tier_level: "Tier Level",
form_tier_level_hint: "Higher number = more features and higher rank",
form_monthly_price: "Monthly Price",
form_yearly_price: "Yearly Price",
form_currency: "Currency",
form_subtitle: "Subtitle / Description",
form_subtitle_placeholder: "e.g. Ideal for small businesses",
form_badge: "Badge Text",
form_badge_placeholder: "e.g. Most Popular",
form_is_custom: "Custom Package (not public)",
singleton_rules: "Singleton Rules",
form_is_default_fallback: "Default Fallback Package — expired subscriptions fall back to this",
form_trial_days: "Trial Days on Signup",
form_trial_days_hint: "New organizations get this many free days. Only one package can have > 0.",
per_region_pricing: "Per-Region Pricing",
smart_calculator: "Smart Price Calculator",
calc_net_price: "Net Price",
calc_vat_rate: "VAT Rate",
calc_currency: "Currency",
calc_net: "Net",
calc_vat: "VAT",
calc_gross: "Gross",
calc_apply: "Apply to selected region",
add_zone: "Add New Zone",
add_zone_select: "Select country code...",
add_zone_already_exists: "This region already exists in the package pricing!"
};
var garages = {
title: "Garages CRM",
subtitle: "Garage list, package management and status changes",
total_garages: "Total Garages",
private_garages: "Private Garages",
corporate_garages: "Corporate Garages",
search_placeholder: "Search by name, contact or email...",
all_tiers: "All packages",
all_types: "All types",
type_individual: "Private (Individual)",
type_corporate: "Corporate",
company_name: "Company Name",
email: "Email",
status: "Status",
current_package: "Current Package",
expiration_date: "Expiration Date",
actions: "Actions",
active: "Active",
inactive: "Inactive",
suspended: "Suspended",
change_package: "Change Package",
manage_subscription: "Manage Subscription",
view: "View",
activate: "Activate",
deactivate: "Deactivate",
no_results: "No garages match your search.",
loading: "Loading garages...",
retry: "Retry",
members: "members",
free_fallback: "Free / Fallback",
expires: "Expires",
select_package: "Select Package",
select_package_placeholder: "Select a subscription package...",
custom_expiration: "Custom Expiration Date",
optional: "optional",
custom_expiration_hint: "Leave empty for default duration (e.g. 30 days). For 2-5 year B2B deals, set a custom date!",
cancel: "Cancel",
save: "Save",
saving: "Saving...",
subscription_updated: "subscription updated successfully!",
view_details: "Details",
indefinite: "Indefinite",
addons_title: "Add-ons",
addon_vehicles: "Extra Vehicle",
addon_branches: "Extra Branch",
addon_users: "Extra Employee",
active_addons: "Active Add-ons",
no_active_addons: "No active add-ons",
addon_vehicles_expiration: "Extra Vehicle Expiration",
addon_branches_expiration: "Extra Branch Expiration",
addon_users_expiration: "Extra Employee Expiration",
addon_expiration_hint: "If empty, existing expiration dates remain.",
details: {
loading: "Loading garage details...",
retry: "Retry",
back: "Back to garages",
company_info: "Company Info",
company_name: "Company Name",
display_name: "Display Name",
org_type: "Organization Type",
tax_number: "Tax Number",
reg_number: "Registration Number",
created_at: "Created At",
address: "Address",
subscription_info: "Subscription Status",
tier_name: "Package",
tier_level: "Level",
level_n: "Level {n}",
expires_at: "Expires",
asset_limit: "Vehicle Limit",
vehicles: "vehicles",
no_subscription: "No active subscription",
contact_info: "Contact Info",
contact_name: "Contact Name",
contact_role: "Role",
contact_department: "Department",
contact_phone: "Contact Phone",
no_contact: "No primary contact person",
edit_details: "Edit Details",
save: "Save",
generalTab: "General",
employeesTab: "Employees",
fleetTab: "Fleet",
analyticsTab: "Analytics",
subscriptionTab: "Subscription",
editBasicTab: "Basic Info",
editContactTab: "Contact",
editAddressTab: "Addresses",
zip: "ZIP Code",
city: "City",
street_name: "Street",
street_type: "Street Type",
house_number: "House Number",
coming_soon: "This feature will be available soon...",
missing_data_title: "Missing Data",
missing_data_desc: "The garage profile is incomplete. Please fill in the missing fields.",
missing_data_activation_required: "To activate the garage, the following data must be provided:",
missing_tax_number: "Tax Number",
missing_billing: "Billing Address",
missing_contact_email: "Contact Email",
missing_contact_phone: "Contact Phone",
missing_data_count: "{count} fields missing",
contact_person_name: "Contact Person Name",
contact_email: "Contact Email",
billing_address: "Billing Address",
billing_zip: "ZIP Code",
billing_city: "City",
billing_street_name: "Street",
billing_street_type: "Street Type",
billing_house_number: "House Number",
notification_address: "Notification Address",
notification_zip: "ZIP Code",
notification_city: "City",
notification_street_name: "Street",
notification_street_type: "Street Type",
notification_house_number: "House Number",
tab_basic: "Basic Info",
tab_contact: "Contact",
tab_addresses: "Addresses",
basic_info: "Basic Info",
contact_section: "Contact Person",
addresses_section: "Addresses",
vehicles_used: "Vehicles",
branches_used: "Branches",
employees_used: "Employees",
branches: "branches",
employees: "employees",
status: "Status",
subscription_history: "Subscription History",
history_date: "Date",
history_package: "Package",
history_action: "Action",
history_status: "Status",
no_subscription_history: "No subscription history yet."
},
analytics: {
ltv: "Lifetime Value (LTV)",
mrr: "Monthly Revenue (MRR)",
monthly_recurring: "Monthly recurring revenue",
outstanding: "Outstanding",
all_settled: "All invoices settled",
earned_credits: "Earned Credits",
contribution_xp: "XP earned from platform contributions",
invited_companies: "Invited Companies",
companies_joined: "Companies joined via your invite",
validated_garages: "Validated Garages",
garages_confirmed: "Garages successfully verified",
utilization: "Utilization",
vehicle_quota: "Vehicle Quota",
employee_quota: "Employee Quota",
utilized: "utilized",
marketplace_engagement: "Marketplace & Engagement",
avg_rating: "Average Rating",
reviews: "Reviews",
reviews_count: "reviews",
last_activity: "Last Activity",
last_login_mock: "2 hours ago",
services_30d: "Services Completed (30 days)"
},
employees: {
title: "Employees",
total_count: "{count} employees",
name: "Name",
email_phone: "Email / Phone",
role: "Role",
status: "Status",
actions: "Actions",
edit_role: "Edit",
remove: "Remove",
no_employees: "No employees assigned to this garage.",
edit_role_title: "Edit Employee Role",
editRoleTitle: "Edit Employee Role",
editRoleFor: "Change role for {name}",
cancel: "Cancel",
save: "Save Changes",
saveRole: "Save Role",
saving: "Saving...",
status_active: "Active",
status_inactive: "Inactive",
remove_title: "Remove Employee",
removeTitle: "Remove Employee",
remove_confirm: "Are you sure you want to remove \"{name}\" from this garage?",
removeConfirm: "Are you sure you want to remove \"{name}\" from this garage?",
remove_btn: "Remove",
removing: "Removing...",
add_employee: "Add Employee",
addTitle: "Add New Employee",
email: "Email Address",
emailPlaceholder: "Enter email address...",
roleMember: "Member",
roleManager: "Manager",
roleAdmin: "Admin",
roleOwner: "Owner",
add: "Add Employee",
adding: "Adding..."
},
fleet: {
title: "Fleet",
total_vehicles: "{count} vehicles total",
plate: "Plate",
brand: "Brand",
model: "Model",
brand_model: "Brand & Model",
year: "Year",
status: "Status",
vin: "VIN",
no_vehicles: "No vehicles assigned to this garage yet.",
no_fleet_access: "You don't have permission to view fleet data."
}
};
var gamification = {
badges: {
title: "Badges",
subtitle: "Badge Management — CRUD",
loading: "Loading badges...",
error: "Failed to load badges.",
retry: "Retry",
create: "New Badge",
no_items: "No badges yet.",
id: "ID",
name: "Name",
description: "Description",
icon: "Icon",
actions: "Actions",
edit: "Edit",
"delete": "Delete",
cancel: "Cancel",
save: "Save",
create_title: "Create Badge",
edit_title: "Edit Badge",
name_placeholder: "Badge name",
desc_placeholder: "Badge description",
icon_placeholder: "Icon URL",
icon_hint: "Optional. The icon URL for the badge.",
icon_preview: "Icon preview",
create_btn: "Create",
delete_title: "Delete Badge",
delete_confirm: "Are you sure you want to delete this badge?",
delete_btn: "Delete",
created: "Badge created!",
updated: "Badge updated!",
deleted: "Badge deleted!",
save_error: "Failed to save badge.",
delete_error: "Failed to delete badge.",
unknown_error: "Unknown error"
},
competitions: {
title: "Competitions",
subtitle: "Seasonal competition management",
loading: "Loading competitions...",
error: "Failed to load competitions.",
retry: "Retry",
create: "New Competition",
no_items: "No competitions created yet.",
create_first: "Create First Competition",
season_filter: "Season Filter:",
all_seasons: "All Seasons",
active_badge: "(Active)",
status_active: "Active",
status_draft: "Draft",
status_completed: "Completed",
status_cancelled: "Cancelled",
view_rules: "View Rules",
edit: "Edit",
cancel: "Cancel",
save: "Save",
create_title: "Create Competition",
edit_title: "Edit Competition",
name: "Name",
name_placeholder: "e.g. Q1 Service Submission Contest",
description: "Description",
desc_placeholder: "Competition description...",
season: "Season",
select_season: "Select a season",
start_date: "Start Date",
end_date: "End Date",
status: "Status",
rules: "Rules (JSON)",
rules_placeholder: "type: service_submission, points_multiplier: 1.5",
invalid_json: "Invalid JSON format!",
create_btn: "Create",
season_id_label: "Season ID:",
save_error: "Failed to save competition."
},
config: {
title: "System Config",
subtitle: "Gamification master configuration editor",
loading: "Loading configuration...",
error: "Failed to load configuration.",
last_save: "Last saved:",
saving: "Saving...",
save: "Save Configuration",
section_xp: "XP Logic",
section_conversion: "Conversion Logic",
section_penalty: "Penalty Logic",
section_rewards: "Level Rewards",
calculator: "Impact Calculator",
calculator_desc: "Adjust parameters to see estimated impact",
estimated_results: "Estimated Results",
daily_xp: "Daily XP",
xp_for_level: "XP Needed for Level Up",
social_to_credit: "Social → Credit",
days_to_level: "Days to Level Up",
raw_json: "Raw JSON Editor",
apply_json: "Apply JSON",
updated: "Configuration updated!",
save_error: "Failed to save configuration.",
json_applied: "JSON applied to form fields!",
invalid_json: "Invalid JSON: "
},
dashboard: {
title: "Gamification HQ",
subtitle: "Gamification system overview dashboard",
loading: "Loading dashboard...",
error: "Failed to load dashboard data.",
total_users: "Total Users",
active_season: "Active Season",
pending_contributions: "Pending Contributions",
xp_earned_today: "XP Earned Today",
none: "None",
quick_actions: "Quick Actions",
manage_point_rules: "Manage Point Rules",
manage_badges: "Manage Badges",
manage_seasons: "Manage Seasons",
recent_ledger: "Recent Ledger Entries",
no_ledger: "No ledger entries yet.",
top_5: "Top 5 Leaderboard",
full_leaderboard: "Full Leaderboard →",
no_leaderboard: "No leaderboard data yet.",
level: "Level",
xp: "XP",
points: "points"
},
leaderboard: {
title: "Leaderboard",
subtitle: "Gamification leaderboard admin view",
search: "Search",
level: "Level",
min_xp: "Min XP",
sort: "Sort",
sort_xp: "By XP",
sort_points: "By Points",
sort_social: "By Social Points",
sort_level: "By Level",
filter: "Filter",
reset: "Reset",
descending: "Descending",
ascending: "Ascending",
user: "user",
loading: "Loading leaderboard...",
error: "Failed to load leaderboard.",
retry: "Retry",
no_results: "No results match your filters.",
no_results_hint: "Try different filter criteria.",
user_col: "User",
email: "Email",
xp: "XP",
points: "Points",
social: "Social",
penalty: "Penalty",
restriction: "Restriction",
discoveries: "Discoveries",
services: "Services",
updated: "Last Updated",
actions: "Actions",
details: "Details",
prev: "Previous",
next: "Next",
page_of: "/ page",
restriction_mild: "Mild",
restriction_moderate: "Moderate",
restriction_severe: "Severe"
},
ledger: {
title: "Points Ledger",
subtitle: "Gamification points ledger browser",
loading: "Loading ledger...",
error: "Failed to load ledger.",
user_id: "User ID",
date_from: "Date From",
date_to: "Date To",
reason: "Reason",
search: "Search",
clear: "Clear",
csv: "CSV",
no_results: "No results match your filters.",
no_results_hint: "Try different filter criteria.",
id: "ID",
user: "User",
points: "Points",
penalty: "Penalty",
xp: "XP",
source: "Source",
date: "Date",
prev: "Previous",
next: "Next",
of: "of",
showing: "showing",
filtered: "(filtered)",
no_csv_data: "No data for CSV export.",
csv_downloaded: "CSV download started."
},
levels: {
title: "Levels",
subtitle: "Level configuration management — CRUD",
loading: "Loading levels...",
error: "Failed to load level configurations.",
retry: "Retry",
create: "New Level",
no_items: "No level configurations yet.",
level: "Level",
rank: "Rank",
min_points: "Min Points",
type: "Type",
actions: "Actions",
penalty: "Penalty",
normal: "Normal",
tree_diagram: "Level Tree Diagram",
no_tree_data: "No levels to display.",
points: "points",
edit_title: "Edit Level",
create_title: "Create Level",
level_number: "Level Number",
rank_name: "Rank Name",
min_points_label: "Minimum Points",
is_penalty: "Penalty Level",
cancel: "Cancel",
save: "Save",
saving: "Saving...",
updated: "Level updated!",
created: "Level created!",
duplicate_level: "A configuration with this level number already exists.",
save_error: "Failed to save level."
},
params: {
title: "System Parameters",
subtitle: "Gamification category system parameters",
loading: "Loading parameters...",
error: "Failed to load system parameters.",
retry: "Retry",
no_items: "No gamification system parameters.",
key: "Key",
value: "Value",
category: "Category",
scope: "Scope",
scope_id: "Scope ID",
actions: "Actions",
edit: "Edit",
edit_title: "Edit Parameter",
value_label: "Value",
value_placeholder: "Parameter value (JSON or plain text)",
json_detected: "🔹 JSON format detected",
text_value: "🔸 Text value",
cancel: "Cancel",
save: "Save",
saving: "Saving...",
invalid_json: "Invalid JSON format: ",
save_error: "Failed to save parameter.",
updated: "updated!"
},
point_rules: {
title: "Point Rules",
subtitle: "Gamification point rules management — CRUD",
loading: "Loading point rules...",
error: "Failed to load point rules.",
retry: "Retry",
create: "New Point Rule",
no_items: "No point rules yet. Create one with the button above!",
id: "ID",
action_key: "Action Key",
points: "Points",
description: "Description",
status: "Status",
actions: "Actions",
active: "Active",
inactive: "Inactive",
edit: "Edit",
"delete": "Delete (soft-delete)",
edit_title: "Edit Point Rule",
create_title: "New Point Rule",
action_key_label: "Action Key",
action_key_placeholder: "e.g. service_submitted",
points_label: "Point Value",
points_placeholder: "0",
description_label: "Description",
description_placeholder: "Short description of the rule...",
is_active: "Active",
cancel: "Cancel",
save: "Save",
saving: "Saving...",
updated: "Point rule updated!",
created: "Point rule created!",
deleted: "Point rule deactivated!",
duplicate_key: "A rule with this action key already exists.",
save_error: "Failed to save point rule.",
delete_title: "Delete Point Rule",
delete_confirm: "Are you sure you want to deactivate the rule",
delete_btn: "Delete",
deleting: "Deleting..."
},
seasons: {
title: "Seasons",
subtitle: "Gamification season management",
loading: "Loading seasons...",
error: "Failed to load seasons.",
retry: "Retry",
create: "New Season",
no_items: "No seasons created yet.",
create_first: "Create First Season",
active: "Active",
inactive: "Inactive",
created_at: "Created:",
activate: "Activate",
edit: "Edit",
edit_title: "Edit Season",
create_title: "New Season",
name: "Name",
name_placeholder: "e.g. 2026 Q1 Season",
start_date: "Start Date",
end_date: "End Date",
activate_on_create: "Activate on creation",
cancel: "Cancel",
save: "Save",
create_btn: "Create",
activate_title: "Activate Season",
activate_confirm: "Are you sure you want to activate",
activate_warning: "This will deactivate all other seasons.",
activating: "Activating...",
activate_btn: "Activate",
save_error: "Failed to save season."
},
users: {
title: "Gamification Users",
subtitle: "User gamification statistics management",
loading: "Loading users...",
error: "Failed to load user statistics.",
retry: "Retry",
no_results: "No user statistics to display.",
level: "Level",
all_levels: "All Levels",
level_n: "Level {n}",
min_xp: "Minimum XP",
max_xp: "Maximum XP",
penalty: "Penalty",
any: "Any",
only_penalized: "Only penalized",
only_clean: "Only clean",
filter: "Filter",
reset: "Reset",
count: "users",
user_id: "User ID",
xp: "XP",
points: "Points",
restriction: "Restriction",
services: "Services",
discoveries: "Discoveries",
updated: "Last Updated",
actions: "Actions",
details: "Details",
prev: "Previous",
next: "Next",
none: "None",
restriction_mild: "Mild",
restriction_moderate: "Moderate",
restriction_severe: "Severe"
},
user_detail: {
back: "Back to list",
title: "User Gamification Details",
id_label: "ID:",
loading: "Loading user...",
error: "Failed to load user data.",
retry: "Retry",
not_found: "User not found.",
total_xp: "Total XP",
level: "Level",
total_points: "Total Points",
social_points: "Social Points",
penalty_points: "Penalty Points",
restriction_level: "Restriction Level",
penalty_quota: "Penalty Quota",
banned_until: "Banned Until",
no: "No",
services: "Services",
discovered_places: "Discovered Places",
validated_places: "Validated Places",
added_providers: "Added Providers",
penalty_form_title: "Assign Penalty",
penalty_points_label: "Penalty Points",
penalty_reason_label: "Reason",
penalty_reason_placeholder: "Reason for penalty...",
penalty_submit: "Assign Penalty",
penalty_submitting: "Submitting...",
penalty_success: "Penalty successfully assigned: {amount} points.",
penalty_error: "Failed to assign penalty.",
reward_form_title: "Assign Reward",
reward_xp_label: "XP Reward",
reward_social_label: "Social Points Reward",
reward_reason_label: "Reason",
reward_reason_placeholder: "Reason for reward...",
reward_submit: "Assign Reward",
reward_submitting: "Submitting...",
reward_success: "Reward successfully assigned: {xp} XP, {social} social points.",
reward_error: "Failed to assign reward.",
ledger_title: "Points Ledger",
ledger_count: "entries",
ledger_loading: "Loading...",
ledger_empty: "No ledger entries for this user yet.",
ledger_date: "Date",
ledger_points: "Points",
ledger_penalty: "Penalty",
ledger_xp: "XP",
ledger_reason: "Reason",
ledger_source: "Source"
}
};
var users = {
title: "User Management",
subtitle: "User list, search, filters and bulk actions",
loading: "Loading users...",
retry: "Retry",
search_placeholder: "Search by email, name or phone...",
all_statuses: "All statuses",
status_active: "Active",
status_inactive: "Inactive",
status_deleted: "Deleted",
status_banned: "Banned",
all_roles: "All roles",
role_user: "User",
role_admin: "Admin",
role_staff: "Staff",
role_superadmin: "Superadmin",
all_plans: "All plans",
plan_free: "Free",
plan_premium: "Premium",
plan_enterprise: "Enterprise",
total_users: "Total Users",
active_users: "Active Users",
deleted_users: "Deleted Users",
banned_users: "Banned Users",
new_today: "New Today",
filtered_results: "Filtered results",
selected_count: "{count} user(s) selected",
bulk_activate: "Activate",
bulk_deactivate: "Deactivate",
clear_selection: "Clear",
email: "Email",
name: "Name",
role: "Role",
status: "Status",
"package": "Package",
registration: "Registration",
language: "Language",
actions: "Actions",
view: "View",
activate: "Activate",
deactivate: "Deactivate",
no_results: "No users match your search.",
showing: "Showing",
prev: "Previous",
next: "Next",
details: {
loading: "Loading user details...",
retry: "Retry",
back: "Back to Users",
edit: "Edit User",
edit_user: "Edit User",
profile_tab: "Profile",
memberships_tab: "Memberships",
account_info: "Account Information",
user_id: "User ID",
registration_date: "Registration Date",
last_login: "Last Login",
ui_mode: "UI Mode",
region: "Region",
currency: "Currency",
subscription_info: "Subscription Information",
subscription_expires: "Expires At",
scope_level: "Scope Level",
scope_id: "Scope ID",
max_vehicles: "Max Vehicles",
max_garages: "Max Garages",
personal_info: "Personal Information",
last_name: "Last Name",
first_name: "First Name",
phone: "Phone",
birth_place: "Birth Place",
birth_date: "Birth Date",
mothers_name: "Mother's Name",
mothers_first_name: "Mother's First Name",
address: "Address",
zip: "ZIP Code",
city: "City",
street: "Street",
house_number: "House Number",
no_person_record: "No personal information record found for this user.",
memberships: "Organization Memberships",
memberships_count: "{count} membership(s)",
no_memberships: "This user is not a member of any organization.",
org_name: "Organization",
org_role: "Role",
member_status: "Status",
joined_at: "Joined",
verified: "Verified",
verified_yes: "Yes",
verified_no: "No",
preferred_language: "Preferred Language",
is_active: "Active",
is_vip: "VIP",
cancel: "Cancel",
save: "Save Changes",
saving: "Saving..."
}
};
const locale_en_46json_0b63539c = {
permissions: permissions,
packages: packages,
garages: garages,
gamification: gamification,
users: users
};
// @ts-nocheck
const localeCodes = [
"hu",
"en"
];
const localeLoaders = {
hu: [
{
key: "locale_hu_46json_ee06c965",
load: () => Promise.resolve(locale_hu_46json_ee06c965),
cache: true
}
],
en: [
{
key: "locale_en_46json_0b63539c",
load: () => Promise.resolve(locale_en_46json_0b63539c),
cache: true
}
]
};
const vueI18nConfigs = [];
const normalizedLocales = [
{
code: "hu",
iso: "hu-HU",
name: "Magyar",
language: undefined
},
{
code: "en",
iso: "en-GB",
name: "English",
language: undefined
}
];
const setupVueI18nOptions = async (defaultLocale) => {
const options = await loadVueI18nOptions(vueI18nConfigs);
options.locale = defaultLocale || options.locale || "en-US";
options.defaultLocale = defaultLocale;
options.fallbackLocale ??= false;
options.messages ??= {};
for (const locale of localeCodes) {
options.messages[locale] ??= {};
}
return options;
};
function defineNitroPlugin(def) {
return def;
}
function defineRenderHandler(render) {
const runtimeConfig = useRuntimeConfig();
return eventHandler(async (event) => {
const nitroApp = useNitroApp();
const ctx = { event, render, response: void 0 };
await nitroApp.hooks.callHook("render:before", ctx);
if (!ctx.response) {
if (event.path === `${runtimeConfig.app.baseURL}favicon.ico`) {
setResponseHeader(event, "Content-Type", "image/x-icon");
return send(
event,
"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
);
}
ctx.response = await ctx.render(event);
if (!ctx.response) {
const _currentStatus = getResponseStatus(event);
setResponseStatus(event, _currentStatus === 200 ? 500 : _currentStatus);
return send(
event,
"No response returned from render handler: " + event.path
);
}
}
await nitroApp.hooks.callHook("render:response", ctx.response, ctx);
if (ctx.response.headers) {
setResponseHeaders(event, ctx.response.headers);
}
if (ctx.response.statusCode || ctx.response.statusMessage) {
setResponseStatus(
event,
ctx.response.statusCode,
ctx.response.statusMessage
);
}
return ctx.response.body;
});
}
function baseURL() {
return useRuntimeConfig().app.baseURL;
}
function buildAssetsDir() {
return useRuntimeConfig().app.buildAssetsDir;
}
function buildAssetsURL(...path) {
return joinRelativeURL(publicAssetsURL(), buildAssetsDir(), ...path);
}
function publicAssetsURL(...path) {
const app = useRuntimeConfig().app;
const publicBase = app.cdnURL || app.baseURL;
return path.length ? joinRelativeURL(publicBase, ...path) : publicBase;
}
function parseAcceptLanguage(value) {
return value.split(",").map((tag) => tag.split(";")[0]).filter(
(tag) => !(tag === "*" || tag === "")
);
}
function createPathIndexLanguageParser(index = 0) {
return (path) => {
const rawPath = typeof path === "string" ? path : path.pathname;
const normalizedPath = rawPath.split("?")[0];
const parts = normalizedPath.split("/");
if (parts[0] === "") {
parts.shift();
}
return parts.length > index ? parts[index] || "" : "";
};
}
function useRuntimeI18n(nuxtApp, event) {
{
return useRuntimeConfig(event).public.i18n;
}
}
function useI18nDetection(nuxtApp) {
const detectBrowserLanguage = useRuntimeI18n().detectBrowserLanguage;
const detect = detectBrowserLanguage || {};
return {
...detect,
enabled: !!detectBrowserLanguage,
cookieKey: detect.cookieKey || "i18n_redirected"
};
}
function resolveRootRedirect(config) {
if (!config) {
return void 0;
}
return {
path: "/" + (isString(config) ? config : config.path).replace(/^\//, ""),
code: !isString(config) && config.statusCode || 302
};
}
function toArray(value) {
return Array.isArray(value) ? value : [value];
}
function createLocaleConfigs(fallbackLocale) {
const localeConfigs = {};
for (const locale of localeCodes) {
const fallbacks = getFallbackLocaleCodes(fallbackLocale, [locale]);
const cacheable = isLocaleWithFallbacksCacheable(locale, fallbacks);
localeConfigs[locale] = { fallbacks, cacheable };
}
return localeConfigs;
}
function getFallbackLocaleCodes(fallback, locales) {
if (fallback === false) {
return [];
}
if (isArray(fallback)) {
return fallback;
}
let fallbackLocales = [];
if (isString(fallback)) {
if (locales.every((locale) => locale !== fallback)) {
fallbackLocales.push(fallback);
}
return fallbackLocales;
}
const targets = [...locales, "default"];
for (const locale of targets) {
if (locale in fallback == false) {
continue;
}
fallbackLocales = [...fallbackLocales, ...fallback[locale].filter(Boolean)];
}
return fallbackLocales;
}
function isLocaleCacheable(locale) {
return localeLoaders[locale] != null && localeLoaders[locale].every((loader) => loader.cache !== false);
}
function isLocaleWithFallbacksCacheable(locale, fallbackLocales) {
return isLocaleCacheable(locale) && fallbackLocales.every((fallbackLocale) => isLocaleCacheable(fallbackLocale));
}
function getDefaultLocaleForDomain(host) {
return normalizedLocales.find((l) => !!l.defaultForDomains?.includes(host))?.code;
}
const isSupportedLocale = (locale) => localeCodes.includes(locale || "");
function useI18nContext(event) {
if (event.context.nuxtI18n == null) {
throw new Error("Nuxt I18n server context has not been set up yet.");
}
return event.context.nuxtI18n;
}
function tryUseI18nContext(event) {
return event.context.nuxtI18n;
}
const getHost = (event) => getRequestURL(event, { xForwardedHost: true }).host;
async function initializeI18nContext(event) {
const runtimeI18n = useRuntimeI18n(void 0, event);
const defaultLocale = runtimeI18n.defaultLocale || "";
const options = await setupVueI18nOptions(getDefaultLocaleForDomain(getHost(event)) || defaultLocale);
const localeConfigs = createLocaleConfigs(options.fallbackLocale);
const ctx = createI18nContext();
ctx.vueI18nOptions = options;
ctx.localeConfigs = localeConfigs;
event.context.nuxtI18n = ctx;
return ctx;
}
function createI18nContext() {
return {
messages: {},
slp: {},
localeConfigs: {},
trackMap: {},
vueI18nOptions: void 0,
trackKey(key, locale) {
this.trackMap[locale] ??= /* @__PURE__ */ new Set();
this.trackMap[locale].add(key);
}
};
}
function matchBrowserLocale(locales, browserLocales) {
const matchedLocales = [];
for (const [index, browserCode] of browserLocales.entries()) {
const matchedLocale = locales.find((l) => l.language?.toLowerCase() === browserCode.toLowerCase());
if (matchedLocale) {
matchedLocales.push({ code: matchedLocale.code, score: 1 - index / browserLocales.length });
break;
}
}
for (const [index, browserCode] of browserLocales.entries()) {
const languageCode = browserCode.split("-")[0].toLowerCase();
const matchedLocale = locales.find((l) => l.language?.split("-")[0].toLowerCase() === languageCode);
if (matchedLocale) {
matchedLocales.push({ code: matchedLocale.code, score: 0.999 - index / browserLocales.length });
break;
}
}
return matchedLocales;
}
function compareBrowserLocale(a, b) {
if (a.score === b.score) {
return b.code.length - a.code.length;
}
return b.score - a.score;
}
function findBrowserLocale(locales, browserLocales) {
const matchedLocales = matchBrowserLocale(
locales.map((l) => ({ code: l.code, language: l.language || l.code })),
browserLocales
);
return matchedLocales.sort(compareBrowserLocale).at(0)?.code ?? "";
}
const appHead = {"meta":[{"name":"viewport","content":"width=device-width, initial-scale=1"},{"charset":"utf-8"}],"link":[],"style":[],"script":[],"noscript":[]};
const appRootTag = "div";
const appRootAttrs = {"id":"__nuxt"};
const appTeleportTag = "div";
const appTeleportAttrs = {"id":"teleports"};
const appId = "nuxt-app";
const separator = "___";
const pathLanguageParser = createPathIndexLanguageParser(0);
const getLocaleFromRoutePath = (path) => pathLanguageParser(path);
const getLocaleFromRouteName = (name) => name.split(separator).at(1) ?? "";
function normalizeInput(input) {
return typeof input !== "object" ? String(input) : String(input?.name || input?.path || "");
}
function getLocaleFromRoute(route) {
const input = normalizeInput(route);
if (input[0] === "/") {
return getLocaleFromRoutePath(input);
}
const fromName = getLocaleFromRouteName(input);
if (fromName) {
return fromName;
}
if (typeof route === "object" && route?.path) {
return getLocaleFromRoutePath(String(route.path));
}
return "";
}
function matchDomainLocale(locales, host, pathLocale) {
const normalizeDomain = (domain = "") => domain.replace(/https?:\/\//, "");
const matches = locales.filter(
(locale) => normalizeDomain(locale.domain) === host || toArray(locale.domains).includes(host)
);
if (matches.length <= 1) {
return matches[0]?.code;
}
return (
// match by current path locale
matches.find((l) => l.code === pathLocale)?.code || matches.find((l) => l.defaultForDomains?.includes(host) ?? l.domainDefault)?.code
);
}
const getCookieLocale = (event, cookieName) => (getCookie(event, cookieName)) || void 0;
const getRouteLocale = (event, route) => getLocaleFromRoute(route);
const getHeaderLocale = (event) => findBrowserLocale(normalizedLocales, parseAcceptLanguage(getRequestHeader(event, "accept-language") || ""));
const getHostLocale = (event, path, domainLocales) => {
const host = getRequestURL(event, { xForwardedHost: true }).host;
const locales = normalizedLocales.map((l) => ({
...l,
domain: domainLocales[l.code]?.domain ?? l.domain
}));
return matchDomainLocale(locales, host, getLocaleFromRoutePath(path));
};
const useDetectors = (event, config, nuxtApp) => {
if (!event) {
throw new Error("H3Event is required for server-side locale detection");
}
const runtimeI18n = useRuntimeI18n();
return {
cookie: () => getCookieLocale(event, config.cookieKey),
header: () => getHeaderLocale(event) ,
navigator: () => void 0,
host: (path) => getHostLocale(event, path, runtimeI18n.domainLocales),
route: (path) => getRouteLocale(event, path)
};
};
// Generated by @nuxtjs/i18n
const pathToI18nConfig = {};
const i18nPathToPath = {};
const disabledI18nPathToPath = {};
const formatTrailingSlash = withoutTrailingSlash;
const matcher = createRouterMatcher([], {});
for (const path of Object.keys(i18nPathToPath)) {
matcher.addRoute({ path, component: () => "", meta: {} });
}
const disabledI18nMatcher = createRouterMatcher([], {});
for (const path of Object.keys(disabledI18nPathToPath)) {
disabledI18nMatcher.addRoute({ path, component: () => "", meta: {} });
}
const getI18nPathToI18nPath = (path, locale) => {
if (!path || !locale) {
return;
}
const plainPath = i18nPathToPath[path];
const i18nConfig = pathToI18nConfig[plainPath];
if (i18nConfig && i18nConfig[locale]) {
return i18nConfig[locale] === true ? plainPath : i18nConfig[locale];
}
};
function isExistingNuxtRoute(path) {
if (path === "") {
return;
}
if (path.endsWith("/__nuxt_error")) {
return;
}
const disabledI18nResolvedMatch = disabledI18nMatcher.resolve({ path }, { path: "/", name: "", matched: [], params: {}, meta: {} });
if (disabledI18nResolvedMatch.matched.length > 0) {
return;
}
const resolvedMatch = matcher.resolve({ path }, { path: "/", name: "", matched: [], params: {}, meta: {} });
return resolvedMatch.matched.length > 0 ? resolvedMatch : void 0;
}
function matchLocalized(path, locale, defaultLocale) {
if (path === "") {
return;
}
const parsed = parsePath(path);
const resolvedMatch = matcher.resolve(
{ path: parsed.pathname || "/" },
{ path: "/", name: "", matched: [], params: {}, meta: {} }
);
if (resolvedMatch.matched.length > 0) {
const alternate = getI18nPathToI18nPath(resolvedMatch.matched[0].path, locale);
const match = matcher.resolve(
{ params: resolvedMatch.params },
{ path: alternate || "/", name: "", matched: [], params: {}, meta: {} }
);
return formatTrailingSlash(withLeadingSlash(joinURL("", match.path)), true);
}
}
function* detect(detectors, detection, path) {
if (detection.enabled) {
yield { locale: detectors.cookie(), source: "cookie" };
yield { locale: detectors.header(), source: "header" };
}
yield { locale: detection.fallbackLocale, source: "fallback" };
}
function createRedirectResponse(event, dest, code) {
event.node.res.setHeader("location", dest);
event.node.res.statusCode = sanitizeStatusCode(code, event.node.res.statusCode);
return {
headers: event.node.res.getHeaders(),
statusCode: event.node.res.statusCode,
body: `<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=${dest.replace(/"/g, "%22")}"></head></html>`
};
}
const _HSLR6LVYB6Jxg8OzRp1aUz6fuSwaQ2FVuwBtHNuoR0w = defineNitroPlugin(async (nitro) => {
const runtimeI18n = useRuntimeI18n();
const rootRedirect = resolveRootRedirect(runtimeI18n.rootRedirect);
runtimeI18n.defaultLocale || "";
try {
const cacheStorage = useStorage("cache");
const cachedKeys = await cacheStorage.getKeys("nitro:handlers:i18n");
await Promise.all(cachedKeys.map((key) => cacheStorage.removeItem(key)));
} catch {
}
const detection = useI18nDetection();
const cookieOptions = {
path: "/",
domain: detection.cookieDomain || void 0,
maxAge: 60 * 60 * 24 * 365,
sameSite: "lax",
secure: detection.cookieSecure
};
const createBaseUrlGetter = () => {
isFunction(runtimeI18n.baseUrl) ? "" : runtimeI18n.baseUrl || "";
if (isFunction(runtimeI18n.baseUrl)) {
return () => "";
}
return (event, defaultLocale) => {
return "";
};
};
function resolveRedirectPath(event, path, pathLocale, defaultLocale, detector) {
let locale = "";
for (const detected of detect(detector, detection, event.path)) {
if (detected.locale && isSupportedLocale(detected.locale)) {
locale = detected.locale;
break;
}
}
locale ||= defaultLocale;
function getLocalizedMatch(locale2) {
const res = matchLocalized(path || "/", locale2);
if (res && res !== event.path) {
return res;
}
}
let resolvedPath = void 0;
let redirectCode = 302;
const requestURL = getRequestURL(event);
if (rootRedirect && requestURL.pathname === "/") {
locale = detection.enabled && locale || defaultLocale;
resolvedPath = isSupportedLocale(detector.route(rootRedirect.path)) && rootRedirect.path || matchLocalized(rootRedirect.path, locale);
redirectCode = rootRedirect.code;
} else if (runtimeI18n.redirectStatusCode) {
redirectCode = runtimeI18n.redirectStatusCode;
}
switch (detection.redirectOn) {
case "root":
if (requestURL.pathname !== "/") {
break;
}
// fallthrough (root has no prefix)
case "no prefix":
if (pathLocale) {
break;
}
// fallthrough to resolve
case "all":
resolvedPath ??= getLocalizedMatch(locale);
break;
}
if (requestURL.pathname === "/" && "no_prefix" === "prefix") ;
return { path: resolvedPath, code: redirectCode, locale };
}
const baseUrlGetter = createBaseUrlGetter();
nitro.hooks.hook("request", async (event) => {
await initializeI18nContext(event);
});
nitro.hooks.hook("render:before", async (context) => {
const { event } = context;
const ctx = useI18nContext(event);
const url = getRequestURL(event);
const detector = useDetectors(event, detection);
const localeSegment = detector.route(event.path);
const pathLocale = isSupportedLocale(localeSegment) && localeSegment || void 0;
const path = (pathLocale && url.pathname.slice(pathLocale.length + 1)) ?? url.pathname;
if (!url.pathname.includes("/_i18n") && !isExistingNuxtRoute(path)) {
return;
}
const resolved = resolveRedirectPath(event, path, pathLocale, ctx.vueI18nOptions.defaultLocale, detector);
if (resolved.path && resolved.path !== url.pathname) {
ctx.detectLocale = resolved.locale;
detection.useCookie && setCookie(event, detection.cookieKey, resolved.locale, cookieOptions);
context.response = createRedirectResponse(
event,
joinURL(baseUrlGetter(event, ctx.vueI18nOptions.defaultLocale), resolved.path + url.search),
resolved.code
);
return;
}
});
nitro.hooks.hook("render:html", (htmlContext, { event }) => {
tryUseI18nContext(event);
});
});
const plugins = [
_HSLR6LVYB6Jxg8OzRp1aUz6fuSwaQ2FVuwBtHNuoR0w
];
const assets = {
"/logo.svg": {
"type": "image/svg+xml",
"etag": "\"1c93-1cv7aKDbuz99JYhQ43U9hm4KE3Q\"",
"mtime": "2026-06-30T00:18:16.396Z",
"size": 7315,
"path": "../public/logo.svg"
},
"/_nuxt/15rOo9Uq.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"1621-XL8w6JpeQMsjOhTe9UC9y1cfETA\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 5665,
"path": "../public/_nuxt/15rOo9Uq.js"
},
"/_nuxt/B0cOE-5l.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"9bba-NuHGoCXBU9W8OUxL7Bj6rGLoL00\"",
"mtime": "2026-06-30T00:18:16.389Z",
"size": 39866,
"path": "../public/_nuxt/B0cOE-5l.js"
},
"/_nuxt/BGJXam6L.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"9d2b-pmSEh+S8dgW4azpdCbuWiellxhc\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 40235,
"path": "../public/_nuxt/BGJXam6L.js"
},
"/_nuxt/BUr2qI1j.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"399f-qy0wRLRAaPiQmbewFREU54FTlC8\"",
"mtime": "2026-06-30T00:18:16.390Z",
"size": 14751,
"path": "../public/_nuxt/BUr2qI1j.js"
},
"/_nuxt/Bih4sFwO.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"d45-edtJd8qUD5O41wqHPdxG4Lxgx64\"",
"mtime": "2026-06-30T00:18:16.390Z",
"size": 3397,
"path": "../public/_nuxt/Bih4sFwO.js"
},
"/_nuxt/BSOl8Atk.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"2d26-QeNktneIRQCNG/da6gxsb8ZYorU\"",
"mtime": "2026-06-30T00:18:16.390Z",
"size": 11558,
"path": "../public/_nuxt/BSOl8Atk.js"
},
"/_nuxt/Bn2ryKUU.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"4adc-dJGH8f0txJS0MU3RllWgbViuXPY\"",
"mtime": "2026-06-30T00:18:16.390Z",
"size": 19164,
"path": "../public/_nuxt/Bn2ryKUU.js"
},
"/_nuxt/BrmL0SWZ.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"2779-kdaYJ1oIjyURygEUsDIWwSIDBrw\"",
"mtime": "2026-06-30T00:18:16.390Z",
"size": 10105,
"path": "../public/_nuxt/BrmL0SWZ.js"
},
"/_nuxt/BMplCfh_.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"41180-xgQxID0jzP8T4XmYWloX+RmlWvo\"",
"mtime": "2026-06-30T00:18:16.390Z",
"size": 266624,
"path": "../public/_nuxt/BMplCfh_.js"
},
"/_nuxt/C1E7awHm.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"220d-/sHiYzkLd0t2RNB69/j9Cw6M+EY\"",
"mtime": "2026-06-30T00:18:16.391Z",
"size": 8717,
"path": "../public/_nuxt/C1E7awHm.js"
},
"/_nuxt/Bv5FHd8A.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"1e6-Mi+wCFX+c7Z+a70KNh/5gGtzPQI\"",
"mtime": "2026-06-30T00:18:16.391Z",
"size": 486,
"path": "../public/_nuxt/Bv5FHd8A.js"
},
"/_nuxt/CGypILv6.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"320e-kC2x2ibXrNTp7kwmk+YQ1F37+oA\"",
"mtime": "2026-06-30T00:18:16.391Z",
"size": 12814,
"path": "../public/_nuxt/CGypILv6.js"
},
"/_nuxt/CJmlBuup.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"3a94-p/Ssvax2CWYbsdPHYzX9iK5Y+EI\"",
"mtime": "2026-06-30T00:18:16.391Z",
"size": 14996,
"path": "../public/_nuxt/CJmlBuup.js"
},
"/_nuxt/CUXMJ-zd.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"3cdf-/hKiZYGjMX7aU3WcjR2fo5Hg5OM\"",
"mtime": "2026-06-30T00:18:16.391Z",
"size": 15583,
"path": "../public/_nuxt/CUXMJ-zd.js"
},
"/_nuxt/CJMCLMKk.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"4358-mdGbWP3IIfp8v3jTZx+WIn1G6TI\"",
"mtime": "2026-06-30T00:18:16.391Z",
"size": 17240,
"path": "../public/_nuxt/CJMCLMKk.js"
},
"/_nuxt/CrbW--3P.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"ee-cX60EI87sbiLzRuohrMFmujcUxw\"",
"mtime": "2026-06-30T00:18:16.391Z",
"size": 238,
"path": "../public/_nuxt/CrbW--3P.js"
},
"/_nuxt/CX89BmAa.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"36da-UTI/h3pJ9qvCYiUIODQnEcs2Jl0\"",
"mtime": "2026-06-30T00:18:16.391Z",
"size": 14042,
"path": "../public/_nuxt/CX89BmAa.js"
},
"/_nuxt/CefVczEW.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"26e5-0fbPQY17puMKSjWKeTe9QWTfyUs\"",
"mtime": "2026-06-30T00:18:16.391Z",
"size": 9957,
"path": "../public/_nuxt/CefVczEW.js"
},
"/_nuxt/D5UKrFBE.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"2857-rBC6ZK1VQFK6n/tr2GBaE3bQOpw\"",
"mtime": "2026-06-30T00:18:16.391Z",
"size": 10327,
"path": "../public/_nuxt/D5UKrFBE.js"
},
"/_nuxt/DFeMqB9v.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"eb2-L2s8jmiiNbDm/Wc9wLPz8vjxmvo\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 3762,
"path": "../public/_nuxt/DFeMqB9v.js"
},
"/_nuxt/CvHtXo6X.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"4575-4sNh4lDobXR9OYtvuwcM3ala0UY\"",
"mtime": "2026-06-30T00:18:16.391Z",
"size": 17781,
"path": "../public/_nuxt/CvHtXo6X.js"
},
"/_nuxt/DJrjUIdP.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"689-EQgWeMMeuoftc4SPHxF0bAoa/q0\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 1673,
"path": "../public/_nuxt/DJrjUIdP.js"
},
"/_nuxt/DP0xHAZ9.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"15e90-VeCcL5ARvoBUssa2DkNp35TpE2c\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 89744,
"path": "../public/_nuxt/DP0xHAZ9.js"
},
"/_nuxt/DoGvoIta.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"cf5-ZuPea57R7aQS3fzm5YX+qYQhxcc\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 3317,
"path": "../public/_nuxt/DoGvoIta.js"
},
"/_nuxt/DlAUqK2U.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"5b-eFCz/UrraTh721pgAl0VxBNR1es\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 91,
"path": "../public/_nuxt/DlAUqK2U.js"
},
"/_nuxt/DlsU4vEK.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"2f9e-oxwp7Npw1jkjIgYe7mt3+AdUQrc\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 12190,
"path": "../public/_nuxt/DlsU4vEK.js"
},
"/_nuxt/DljN7UFd.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"86ad-5zxEMaGHz6UNggVeJtSm/NacXI4\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 34477,
"path": "../public/_nuxt/DljN7UFd.js"
},
"/_nuxt/LFK12hZo.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"3151-P6cxbVQBBrXdz6Q2uB1Y17+rHos\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 12625,
"path": "../public/_nuxt/LFK12hZo.js"
},
"/_nuxt/DoxiXr8X.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"9dc1-Arf67JGWHoUCbTwE44Sg8aWAK1E\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 40385,
"path": "../public/_nuxt/DoxiXr8X.js"
},
"/_nuxt/QcXNNtwJ.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"4e2d-/ZQc6vVyOh2RR+tZky+1bZBT/5o\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 20013,
"path": "../public/_nuxt/QcXNNtwJ.js"
},
"/_nuxt/SEfBnA2b.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"a62e-NHaCad6BO34WbKhoykWUG46PhLk\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 42542,
"path": "../public/_nuxt/SEfBnA2b.js"
},
"/_nuxt/VxZautWX.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"445-oUncGnuGoRNGO/l422cdsNQ0vXw\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 1093,
"path": "../public/_nuxt/VxZautWX.js"
},
"/_nuxt/entry.KrfumMBl.css": {
"type": "text/css; charset=utf-8",
"etag": "\"19-60Qvpq/4eRs/sHLgNwhHUEqqm/o\"",
"mtime": "2026-06-30T00:18:16.393Z",
"size": 25,
"path": "../public/_nuxt/entry.KrfumMBl.css"
},
"/_nuxt/VRBzZU6y.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"66c9-Oj2MTAqfJFXvmQlZsD98FS1/5jQ\"",
"mtime": "2026-06-30T00:18:16.392Z",
"size": 26313,
"path": "../public/_nuxt/VRBzZU6y.js"
},
"/_nuxt/config.BuyvRcla.css": {
"type": "text/css; charset=utf-8",
"etag": "\"b6-aSd6q1fPl/EmZiGdMirdFEfUWm4\"",
"mtime": "2026-06-30T00:18:16.393Z",
"size": 182,
"path": "../public/_nuxt/config.BuyvRcla.css"
},
"/_nuxt/error-404.DL_4WIao.css": {
"type": "text/css; charset=utf-8",
"etag": "\"dca-KnjyV0UbpsrliiJzZx69defY74k\"",
"mtime": "2026-06-30T00:18:16.393Z",
"size": 3530,
"path": "../public/_nuxt/error-404.DL_4WIao.css"
},
"/_nuxt/error-500.I1Dtv2V5.css": {
"type": "text/css; charset=utf-8",
"etag": "\"75a-vEGyJqldBVJrnMfcLsrGaHcxYl0\"",
"mtime": "2026-06-30T00:18:16.393Z",
"size": 1882,
"path": "../public/_nuxt/error-500.I1Dtv2V5.css"
},
"/_nuxt/ledger.BFl7YEel.css": {
"type": "text/css; charset=utf-8",
"etag": "\"b6-uZt5V50O4Dsn6jVEP06mgXOWh0I\"",
"mtime": "2026-06-30T00:18:16.393Z",
"size": 182,
"path": "../public/_nuxt/ledger.BFl7YEel.css"
},
"/_nuxt/jkQ9zsLP.js": {
"type": "text/javascript; charset=utf-8",
"etag": "\"318a-Jo9dAKNAyXneLM85z529fJSetM4\"",
"mtime": "2026-06-30T00:18:16.393Z",
"size": 12682,
"path": "../public/_nuxt/jkQ9zsLP.js"
},
"/_nuxt/levels.D8Zzp6B_.css": {
"type": "text/css; charset=utf-8",
"etag": "\"b6-9n6wAsjQSy/HPOYQFTxA+B1Xp80\"",
"mtime": "2026-06-30T00:18:16.393Z",
"size": 182,
"path": "../public/_nuxt/levels.D8Zzp6B_.css"
},
"/_nuxt/point-rules.BINQc_Qs.css": {
"type": "text/css; charset=utf-8",
"etag": "\"b6-6/o4IZsFRW+JJF4AHFwQUsMN4WI\"",
"mtime": "2026-06-30T00:18:16.393Z",
"size": 182,
"path": "../public/_nuxt/point-rules.BINQc_Qs.css"
},
"/_nuxt/parameters.BlLxSA6Z.css": {
"type": "text/css; charset=utf-8",
"etag": "\"b6-Ak8LsrGcnrOu1gTherfdi1oVUsU\"",
"mtime": "2026-06-30T00:18:16.393Z",
"size": 182,
"path": "../public/_nuxt/parameters.BlLxSA6Z.css"
},
"/_nuxt/builds/latest.json": {
"type": "application/json",
"etag": "\"47-cyeqVo4I301CYKSbSQdQpqRI4Xo\"",
"mtime": "2026-06-30T00:18:16.377Z",
"size": 71,
"path": "../public/_nuxt/builds/latest.json"
},
"/_nuxt/builds/meta/dev.json": {
"type": "application/json",
"etag": "\"37-U0bQA0oemqE745skAKUF5+lvetE\"",
"mtime": "2026-06-30T00:18:16.374Z",
"size": 55,
"path": "../public/_nuxt/builds/meta/dev.json"
},
"/_nuxt/builds/meta/f5b6ccee-0c83-43d5-86e7-8dae6c4b4232.json": {
"type": "application/json",
"etag": "\"58-qPBe7SGZAeZtUv2cwZfCG8FYVEo\"",
"mtime": "2026-06-30T00:18:16.373Z",
"size": 88,
"path": "../public/_nuxt/builds/meta/f5b6ccee-0c83-43d5-86e7-8dae6c4b4232.json"
},
"/sf_logo.png": {
"type": "image/png",
"etag": "\"4366a8-5u0A+e1MYT8zegFkKhhzxt5KbGs\"",
"mtime": "2026-06-30T00:18:16.396Z",
"size": 4417192,
"path": "../public/sf_logo.png"
}
};
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(input = "") {
if (!input) {
return input;
}
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
}
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
function cwd() {
if (typeof process !== "undefined" && typeof process.cwd === "function") {
return process.cwd().replace(/\\/g, "/");
}
return "/";
}
const resolve = function(...arguments_) {
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
let resolvedPath = "";
let resolvedAbsolute = false;
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
const path = index >= 0 ? arguments_[index] : cwd();
if (!path || path.length === 0) {
continue;
}
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = isAbsolute(path);
}
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
return `/${resolvedPath}`;
}
return resolvedPath.length > 0 ? resolvedPath : ".";
};
function normalizeString(path, allowAboveRoot) {
let res = "";
let lastSegmentLength = 0;
let lastSlash = -1;
let dots = 0;
let char = null;
for (let index = 0; index <= path.length; ++index) {
if (index < path.length) {
char = path[index];
} else if (char === "/") {
break;
} else {
char = "/";
}
if (char === "/") {
if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
if (res.length > 2) {
const lastSlashIndex = res.lastIndexOf("/");
if (lastSlashIndex === -1) {
res = "";
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
}
lastSlash = index;
dots = 0;
continue;
} else if (res.length > 0) {
res = "";
lastSegmentLength = 0;
lastSlash = index;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += res.length > 0 ? "/.." : "..";
lastSegmentLength = 2;
}
} else {
if (res.length > 0) {
res += `/${path.slice(lastSlash + 1, index)}`;
} else {
res = path.slice(lastSlash + 1, index);
}
lastSegmentLength = index - lastSlash - 1;
}
lastSlash = index;
dots = 0;
} else if (char === "." && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
const isAbsolute = function(p) {
return _IS_ABSOLUTE_RE.test(p);
};
const dirname = function(p) {
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
segments[0] += "/";
}
return segments.join("/") || (isAbsolute(p) ? "/" : ".");
};
function readAsset (id) {
const serverDir = dirname(fileURLToPath(globalThis._importMeta_.url));
return promises.readFile(resolve(serverDir, assets[id].path))
}
const publicAssetBases = {"/_nuxt/builds/meta/":{"maxAge":31536000},"/_nuxt/builds/":{"maxAge":1},"/_nuxt/":{"maxAge":31536000}};
function isPublicAssetURL(id = '') {
if (assets[id]) {
return true
}
for (const base in publicAssetBases) {
if (id.startsWith(base)) { return true }
}
return false
}
function getAsset (id) {
return assets[id]
}
const METHODS = /* @__PURE__ */ new Set(["HEAD", "GET"]);
const EncodingMap = { gzip: ".gz", br: ".br" };
const _oStzCE = eventHandler((event) => {
if (event.method && !METHODS.has(event.method)) {
return;
}
let id = decodePath(
withLeadingSlash(withoutTrailingSlash(parseURL(event.path).pathname))
);
let asset;
const encodingHeader = String(
getRequestHeader(event, "accept-encoding") || ""
);
const encodings = [
...encodingHeader.split(",").map((e) => EncodingMap[e.trim()]).filter(Boolean).sort(),
""
];
for (const encoding of encodings) {
for (const _id of [id + encoding, joinURL(id, "index.html" + encoding)]) {
const _asset = getAsset(_id);
if (_asset) {
asset = _asset;
id = _id;
break;
}
}
}
if (!asset) {
if (isPublicAssetURL(id)) {
removeResponseHeader(event, "Cache-Control");
throw createError$1({ statusCode: 404 });
}
return;
}
if (asset.encoding !== void 0) {
appendResponseHeader(event, "Vary", "Accept-Encoding");
}
const ifNotMatch = getRequestHeader(event, "if-none-match") === asset.etag;
if (ifNotMatch) {
setResponseStatus(event, 304, "Not Modified");
return "";
}
const ifModifiedSinceH = getRequestHeader(event, "if-modified-since");
const mtimeDate = new Date(asset.mtime);
if (ifModifiedSinceH && asset.mtime && new Date(ifModifiedSinceH) >= mtimeDate) {
setResponseStatus(event, 304, "Not Modified");
return "";
}
if (asset.type && !getResponseHeader(event, "Content-Type")) {
setResponseHeader(event, "Content-Type", asset.type);
}
if (asset.etag && !getResponseHeader(event, "ETag")) {
setResponseHeader(event, "ETag", asset.etag);
}
if (asset.mtime && !getResponseHeader(event, "Last-Modified")) {
setResponseHeader(event, "Last-Modified", mtimeDate.toUTCString());
}
if (asset.encoding && !getResponseHeader(event, "Content-Encoding")) {
setResponseHeader(event, "Content-Encoding", asset.encoding);
}
if (asset.size > 0 && !getResponseHeader(event, "Content-Length")) {
setResponseHeader(event, "Content-Length", asset.size);
}
return readAsset(id);
});
const storage = prefixStorage(useStorage(), "i18n");
function cachedFunctionI18n(fn, opts) {
opts = { maxAge: 1, ...opts };
const pending = {};
async function get(key, resolver) {
const isPending = pending[key];
if (!isPending) {
pending[key] = Promise.resolve(resolver());
}
try {
return await pending[key];
} finally {
delete pending[key];
}
}
return async (...args) => {
const key = [opts.name, opts.getKey(...args)].join(":").replace(/:\/$/, ":index");
const maxAge = opts.maxAge ?? 1;
const isCacheable = !opts.shouldBypassCache(...args) && maxAge >= 0;
const cache = isCacheable && await storage.getItemRaw(key);
if (!cache || cache.ttl < Date.now()) {
pending[key] = Promise.resolve(fn(...args));
const value = await get(key, () => fn(...args));
if (isCacheable) {
await storage.setItemRaw(key, { ttl: Date.now() + maxAge * 1e3, value, mtime: Date.now() });
}
return value;
}
return cache.value;
};
}
const _getMessages = async (locale) => {
return { [locale]: await getLocaleMessagesMerged(locale, localeLoaders[locale]) };
};
const _getMessagesCached = cachedFunctionI18n(_getMessages, {
name: "messages",
maxAge: 60 * 60 * 24,
getKey: (locale) => locale,
shouldBypassCache: (locale) => !isLocaleCacheable(locale)
});
const getMessages = _getMessagesCached;
const _getMergedMessages = async (locale, fallbackLocales) => {
const merged = {};
try {
if (fallbackLocales.length > 0) {
const messages = await Promise.all(fallbackLocales.map(getMessages));
for (const message2 of messages) {
deepCopy(message2, merged);
}
}
const message = await getMessages(locale);
deepCopy(message, merged);
return merged;
} catch (e) {
throw new Error("Failed to merge messages: " + e.message);
}
};
const getMergedMessages = cachedFunctionI18n(_getMergedMessages, {
name: "merged-single",
maxAge: 60 * 60 * 24,
getKey: (locale, fallbackLocales) => `${locale}-[${[...new Set(fallbackLocales)].sort().join("-")}]`,
shouldBypassCache: (locale, fallbackLocales) => !isLocaleWithFallbacksCacheable(locale, fallbackLocales)
});
const _getAllMergedMessages = async (locales) => {
const merged = {};
try {
const messages = await Promise.all(locales.map(getMessages));
for (const message of messages) {
deepCopy(message, merged);
}
return merged;
} catch (e) {
throw new Error("Failed to merge messages: " + e.message);
}
};
cachedFunctionI18n(_getAllMergedMessages, {
name: "merged-all",
maxAge: 60 * 60 * 24,
getKey: (locales) => locales.join("-"),
shouldBypassCache: (locales) => !locales.every((locale) => isLocaleCacheable(locale))
});
const _messagesHandler = defineEventHandler(async (event) => {
const locale = getRouterParam(event, "locale");
if (!locale) {
throw createError$1({ status: 400, message: "Locale not specified." });
}
const ctx = useI18nContext(event);
if (ctx.localeConfigs && locale in ctx.localeConfigs === false) {
throw createError$1({ status: 404, message: `Locale '${locale}' not found.` });
}
const messages = await getMergedMessages(locale, ctx.localeConfigs?.[locale]?.fallbacks ?? []);
deepCopy(messages, ctx.messages);
return ctx.messages;
});
const _cachedMessageLoader = defineCachedFunction(_messagesHandler, {
name: "i18n:messages-internal",
maxAge: 60 * 60 * 24,
getKey: (event) => [getRouterParam(event, "locale") ?? "null", getRouterParam(event, "hash") ?? "null"].join("-"),
async shouldBypassCache(event) {
const locale = getRouterParam(event, "locale");
if (locale == null) {
return false;
}
const ctx = tryUseI18nContext(event) || await initializeI18nContext(event);
return !ctx.localeConfigs?.[locale]?.cacheable;
}
});
const _messagesHandlerCached = defineCachedEventHandler(_cachedMessageLoader, {
name: "i18n:messages",
maxAge: 10,
swr: false,
getKey: (event) => [getRouterParam(event, "locale") ?? "null", getRouterParam(event, "hash") ?? "null"].join("-")
});
const _cSDLJw = _messagesHandlerCached;
const _SxA8c9 = defineEventHandler(() => {});
const _lazy_0XwxzV = () => import('../routes/renderer.mjs').then(function (n) { return n.r; });
const handlers = [
{ route: '', handler: _oStzCE, lazy: false, middleware: true, method: undefined },
{ route: '/__nuxt_error', handler: _lazy_0XwxzV, lazy: true, middleware: false, method: undefined },
{ route: '/_i18n/:hash/:locale/messages.json', handler: _cSDLJw, lazy: false, middleware: false, method: undefined },
{ route: '/__nuxt_island/**', handler: _SxA8c9, lazy: false, middleware: false, method: undefined },
{ route: '/**', handler: _lazy_0XwxzV, lazy: true, middleware: false, method: undefined }
];
function createNitroApp() {
const config = useRuntimeConfig();
const hooks = createHooks();
const captureError = (error, context = {}) => {
const promise = hooks.callHookParallel("error", error, context).catch((error_) => {
console.error("Error while capturing another error", error_);
});
if (context.event && isEvent(context.event)) {
const errors = context.event.context.nitro?.errors;
if (errors) {
errors.push({ error, context });
}
if (context.event.waitUntil) {
context.event.waitUntil(promise);
}
}
};
const h3App = createApp({
debug: destr(false),
onError: (error, event) => {
captureError(error, { event, tags: ["request"] });
return errorHandler(error, event);
},
onRequest: async (event) => {
event.context.nitro = event.context.nitro || { errors: [] };
const fetchContext = event.node.req?.__unenv__;
if (fetchContext?._platform) {
event.context = {
_platform: fetchContext?._platform,
// #3335
...fetchContext._platform,
...event.context
};
}
if (!event.context.waitUntil && fetchContext?.waitUntil) {
event.context.waitUntil = fetchContext.waitUntil;
}
event.fetch = (req, init) => fetchWithEvent(event, req, init, { fetch: localFetch });
event.$fetch = (req, init) => fetchWithEvent(event, req, init, {
fetch: $fetch
});
event.waitUntil = (promise) => {
if (!event.context.nitro._waitUntilPromises) {
event.context.nitro._waitUntilPromises = [];
}
event.context.nitro._waitUntilPromises.push(promise);
if (event.context.waitUntil) {
event.context.waitUntil(promise);
}
};
event.captureError = (error, context) => {
captureError(error, { event, ...context });
};
await nitroApp$1.hooks.callHook("request", event).catch((error) => {
captureError(error, { event, tags: ["request"] });
});
},
onBeforeResponse: async (event, response) => {
await nitroApp$1.hooks.callHook("beforeResponse", event, response).catch((error) => {
captureError(error, { event, tags: ["request", "response"] });
});
},
onAfterResponse: async (event, response) => {
await nitroApp$1.hooks.callHook("afterResponse", event, response).catch((error) => {
captureError(error, { event, tags: ["request", "response"] });
});
}
});
const router = createRouter({
preemptive: true
});
const nodeHandler = toNodeListener(h3App);
const localCall = (aRequest) => b(
nodeHandler,
aRequest
);
const localFetch = (input, init) => {
if (!input.toString().startsWith("/")) {
return globalThis.fetch(input, init);
}
return C(
nodeHandler,
input,
init
).then((response) => normalizeFetchResponse(response));
};
const $fetch = createFetch({
fetch: localFetch,
Headers: Headers$1,
defaults: { baseURL: config.app.baseURL }
});
globalThis.$fetch = $fetch;
h3App.use(createRouteRulesHandler({ localFetch }));
for (const h of handlers) {
let handler = h.lazy ? lazyEventHandler(h.handler) : h.handler;
if (h.middleware || !h.route) {
const middlewareBase = (config.app.baseURL + (h.route || "/")).replace(
/\/+/g,
"/"
);
h3App.use(middlewareBase, handler);
} else {
const routeRules = getRouteRulesForPath(
h.route.replace(/:\w+|\*\*/g, "_")
);
if (routeRules.cache) {
handler = cachedEventHandler(handler, {
group: "nitro/routes",
...routeRules.cache
});
}
router.use(h.route, handler, h.method);
}
}
h3App.use(config.app.baseURL, router.handler);
const app = {
hooks,
h3App,
router,
localCall,
localFetch,
captureError
};
return app;
}
function runNitroPlugins(nitroApp2) {
for (const plugin of plugins) {
try {
plugin(nitroApp2);
} catch (error) {
nitroApp2.captureError(error, { tags: ["plugin"] });
throw error;
}
}
}
const nitroApp$1 = createNitroApp();
function useNitroApp() {
return nitroApp$1;
}
runNitroPlugins(nitroApp$1);
const NullObject = /* @__PURE__ */ (() => {
const C = function() {
};
C.prototype = /* @__PURE__ */ Object.create(null);
return C;
})();
function parse(str, options) {
if (typeof str !== "string") {
throw new TypeError("argument str must be a string");
}
const obj = new NullObject();
const opt = options || {};
const dec = opt.decode || decode;
let index = 0;
while (index < str.length) {
const eqIdx = str.indexOf("=", index);
if (eqIdx === -1) {
break;
}
let endIdx = str.indexOf(";", index);
if (endIdx === -1) {
endIdx = str.length;
} else if (endIdx < eqIdx) {
index = str.lastIndexOf(";", eqIdx - 1) + 1;
continue;
}
const key = str.slice(index, eqIdx).trim();
if (opt?.filter && !opt?.filter(key)) {
index = endIdx + 1;
continue;
}
if (void 0 === obj[key]) {
let val = str.slice(eqIdx + 1, endIdx).trim();
if (val.codePointAt(0) === 34) {
val = val.slice(1, -1);
}
obj[key] = tryDecode(val, dec);
}
index = endIdx + 1;
}
return obj;
}
function decode(str) {
return str.includes("%") ? decodeURIComponent(str) : str;
}
function tryDecode(str, decode2) {
try {
return decode2(str);
} catch {
return str;
}
}
const debug = (...args) => {
};
function GracefulShutdown(server, opts) {
opts = opts || {};
const options = Object.assign(
{
signals: "SIGINT SIGTERM",
timeout: 3e4,
development: false,
forceExit: true,
onShutdown: (signal) => Promise.resolve(signal),
preShutdown: (signal) => Promise.resolve(signal)
},
opts
);
let isShuttingDown = false;
const connections = {};
let connectionCounter = 0;
const secureConnections = {};
let secureConnectionCounter = 0;
let failed = false;
let finalRun = false;
function onceFactory() {
let called = false;
return (emitter, events, callback) => {
function call() {
if (!called) {
called = true;
return Reflect.apply(callback, this, arguments);
}
}
for (const e of events) {
emitter.on(e, call);
}
};
}
const signals = options.signals.split(" ").map((s) => s.trim()).filter((s) => s.length > 0);
const once = onceFactory();
once(process, signals, (signal) => {
debug("received shut down signal", signal);
shutdown(signal).then(() => {
if (options.forceExit) {
process.exit(failed ? 1 : 0);
}
}).catch((error) => {
debug("server shut down error occurred", error);
process.exit(1);
});
});
function isFunction(functionToCheck) {
const getType = Object.prototype.toString.call(functionToCheck);
return /^\[object\s([A-Za-z]+)?Function]$/.test(getType);
}
function destroy(socket, force = false) {
if (socket._isIdle && isShuttingDown || force) {
socket.destroy();
if (socket.server instanceof http.Server) {
delete connections[socket._connectionId];
} else {
delete secureConnections[socket._connectionId];
}
}
}
function destroyAllConnections(force = false) {
debug("Destroy Connections : " + (force ? "forced close" : "close"));
let counter = 0;
let secureCounter = 0;
for (const key of Object.keys(connections)) {
const socket = connections[key];
const serverResponse = socket._httpMessage;
if (serverResponse && !force) {
if (!serverResponse.headersSent) {
serverResponse.setHeader("connection", "close");
}
} else {
counter++;
destroy(socket);
}
}
debug("Connections destroyed : " + counter);
debug("Connection Counter : " + connectionCounter);
for (const key of Object.keys(secureConnections)) {
const socket = secureConnections[key];
const serverResponse = socket._httpMessage;
if (serverResponse && !force) {
if (!serverResponse.headersSent) {
serverResponse.setHeader("connection", "close");
}
} else {
secureCounter++;
destroy(socket);
}
}
debug("Secure Connections destroyed : " + secureCounter);
debug("Secure Connection Counter : " + secureConnectionCounter);
}
server.on("request", (req, res) => {
req.socket._isIdle = false;
if (isShuttingDown && !res.headersSent) {
res.setHeader("connection", "close");
}
res.on("finish", () => {
req.socket._isIdle = true;
destroy(req.socket);
});
});
server.on("connection", (socket) => {
if (isShuttingDown) {
socket.destroy();
} else {
const id = connectionCounter++;
socket._isIdle = true;
socket._connectionId = id;
connections[id] = socket;
socket.once("close", () => {
delete connections[socket._connectionId];
});
}
});
server.on("secureConnection", (socket) => {
if (isShuttingDown) {
socket.destroy();
} else {
const id = secureConnectionCounter++;
socket._isIdle = true;
socket._connectionId = id;
secureConnections[id] = socket;
socket.once("close", () => {
delete secureConnections[socket._connectionId];
});
}
});
process.on("close", () => {
debug("closed");
});
function shutdown(sig) {
function cleanupHttp() {
destroyAllConnections();
debug("Close http server");
return new Promise((resolve, reject) => {
server.close((err) => {
if (err) {
return reject(err);
}
return resolve(true);
});
});
}
debug("shutdown signal - " + sig);
if (options.development) {
debug("DEV-Mode - immediate forceful shutdown");
return process.exit(0);
}
function finalHandler() {
if (!finalRun) {
finalRun = true;
if (options.finally && isFunction(options.finally)) {
debug("executing finally()");
options.finally();
}
}
return Promise.resolve();
}
function waitForReadyToShutDown(totalNumInterval) {
debug(`waitForReadyToShutDown... ${totalNumInterval}`);
if (totalNumInterval === 0) {
debug(
`Could not close connections in time (${options.timeout}ms), will forcefully shut down`
);
return Promise.resolve(true);
}
const allConnectionsClosed = Object.keys(connections).length === 0 && Object.keys(secureConnections).length === 0;
if (allConnectionsClosed) {
debug("All connections closed. Continue to shutting down");
return Promise.resolve(false);
}
debug("Schedule the next waitForReadyToShutdown");
return new Promise((resolve) => {
setTimeout(() => {
resolve(waitForReadyToShutDown(totalNumInterval - 1));
}, 250);
});
}
if (isShuttingDown) {
return Promise.resolve();
}
debug("shutting down");
return options.preShutdown(sig).then(() => {
isShuttingDown = true;
cleanupHttp();
}).then(() => {
const pollIterations = options.timeout ? Math.round(options.timeout / 250) : 0;
return waitForReadyToShutDown(pollIterations);
}).then((force) => {
debug("Do onShutdown now");
if (force) {
destroyAllConnections(force);
}
return options.onShutdown(sig);
}).then(finalHandler).catch((error) => {
const errString = typeof error === "string" ? error : JSON.stringify(error);
debug(errString);
failed = true;
throw errString;
});
}
function shutdownManual() {
return shutdown("manual");
}
return shutdownManual;
}
function getGracefulShutdownConfig() {
return {
disabled: !!process.env.NITRO_SHUTDOWN_DISABLED,
signals: (process.env.NITRO_SHUTDOWN_SIGNALS || "SIGTERM SIGINT").split(" ").map((s) => s.trim()),
timeout: Number.parseInt(process.env.NITRO_SHUTDOWN_TIMEOUT || "", 10) || 3e4,
forceExit: !process.env.NITRO_SHUTDOWN_NO_FORCE_EXIT
};
}
function setupGracefulShutdown(listener, nitroApp) {
const shutdownConfig = getGracefulShutdownConfig();
if (shutdownConfig.disabled) {
return;
}
GracefulShutdown(listener, {
signals: shutdownConfig.signals.join(" "),
timeout: shutdownConfig.timeout,
forceExit: shutdownConfig.forceExit,
onShutdown: async () => {
await new Promise((resolve) => {
const timeout = setTimeout(() => {
console.warn("Graceful shutdown timeout, force exiting...");
resolve();
}, shutdownConfig.timeout);
nitroApp.hooks.callHook("close").catch((error) => {
console.error(error);
}).finally(() => {
clearTimeout(timeout);
resolve();
});
});
}
});
}
const cert = process.env.NITRO_SSL_CERT;
const key = process.env.NITRO_SSL_KEY;
const nitroApp = useNitroApp();
const server = cert && key ? new Server({ key, cert }, toNodeListener(nitroApp.h3App)) : new Server$1(toNodeListener(nitroApp.h3App));
const port = destr(process.env.NITRO_PORT || process.env.PORT) || 3e3;
const host = process.env.NITRO_HOST || process.env.HOST;
const path = process.env.NITRO_UNIX_SOCKET;
const listener = server.listen(path ? { path } : { port, host }, (err) => {
if (err) {
console.error(err);
process.exit(1);
}
const protocol = cert && key ? "https" : "http";
const addressInfo = listener.address();
if (typeof addressInfo === "string") {
console.log(`Listening on unix socket ${addressInfo}`);
return;
}
const baseURL = (useRuntimeConfig().app.baseURL || "").replace(/\/$/, "");
const url = `${protocol}://${addressInfo.family === "IPv6" ? `[${addressInfo.address}]` : addressInfo.address}:${addressInfo.port}${baseURL}`;
console.log(`Listening on ${url}`);
});
trapUnhandledNodeErrors();
setupGracefulShutdown(listener, nitroApp);
const nodeServer = {};
export { $fetch$1 as $, destr as A, isEqual as B, sanitizeStatusCode as C, setCookie as D, getCookie as E, deleteCookie as F, getContext as G, baseURL as H, defu as I, createHooks as J, executeAsync as K, getRequestURL as L, createDefu as M, parsePath as N, parseQuery as O, withoutTrailingSlash as P, withTrailingSlash as Q, nodeServer as R, appRootTag as a, buildAssetsURL as b, appRootAttrs as c, appId as d, encodePath as e, defineRenderHandler as f, appTeleportTag as g, appTeleportAttrs as h, getQuery as i, createError$1 as j, appHead as k, getRouteRules as l, getResponseStatusText as m, getResponseStatus as n, useNitroApp as o, publicAssetsURL as p, klona as q, parseURL as r, decodePath as s, hasProtocol as t, useRuntimeConfig as u, isScriptProtocol as v, joinURL as w, withQuery as x, parse as y, getRequestHeader as z };
//# sourceMappingURL=nitro.mjs.map