| import { B as T, V as a, at as join$1, ct as resolve$1, g as writeDevBuildInfo, j as src_default, rt as extname$1 } from "../_build/common.mjs"; | ||
| import { i as debounce } from "../_libs/rc9+c12+dotenv.mjs"; | ||
| import { t as createProxyServer } from "../_libs/httpxy.mjs"; | ||
| import { n as watch$1 } from "../_libs/readdirp+chokidar.mjs"; | ||
| import consola$1 from "consola"; | ||
| import { createReadStream, existsSync } from "node:fs"; | ||
| import { readFile, rm, stat as stat$1 } from "node:fs/promises"; | ||
| import { dirname, resolve } from "node:path"; | ||
| import { joinURL } from "ufo"; | ||
| import { createBrotliCompress, createGzip } from "node:zlib"; | ||
| import { Worker } from "node:worker_threads"; | ||
| import { H3, HTTPError, defineHandler, fromNodeHandler, getRequestIP, getRequestURL, serveStatic, toEventHandler } from "h3"; | ||
| import { Agent } from "undici"; | ||
| import { serve } from "srvx/node"; | ||
| import { ErrorParser } from "youch-core"; | ||
| import { Youch } from "youch"; | ||
| import { SourceMapConsumer } from "source-map"; | ||
| import { FastResponse } from "srvx"; | ||
| //#region src/runner/proxy.ts | ||
| function createHTTPProxy(defaults = {}) { | ||
| const proxy = createProxyServer(defaults); | ||
| proxy.on("proxyReq", (proxyReq, req) => { | ||
| if (!proxyReq.hasHeader("x-forwarded-for")) { | ||
| const address = req.socket.remoteAddress; | ||
| if (address) proxyReq.appendHeader("x-forwarded-for", address); | ||
| } | ||
| if (!proxyReq.hasHeader("x-forwarded-port")) { | ||
| if (req?.socket?.localPort) proxyReq.setHeader("x-forwarded-port", req.socket.localPort); | ||
| } | ||
| if (!proxyReq.hasHeader("x-forwarded-Proto")) { | ||
| const encrypted = (req?.connection)?.encrypted; | ||
| proxyReq.setHeader("x-forwarded-proto", encrypted ? "https" : "http"); | ||
| } | ||
| }); | ||
| return { | ||
| proxy, | ||
| async handleEvent(event, opts) { | ||
| try { | ||
| return await fromNodeHandler((req, res) => proxy.web(req, res, opts))(event); | ||
| } catch (error) { | ||
| event.res.headers.set("refresh", "3"); | ||
| throw new HTTPError({ | ||
| status: 503, | ||
| message: "Dev server is unavailable.", | ||
| cause: error | ||
| }); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| async function fetchAddress(addr, input, inputInit) { | ||
| let url; | ||
| let init; | ||
| if (input instanceof Request) { | ||
| url = new URL(input.url); | ||
| init = { | ||
| method: input.method, | ||
| headers: input.headers, | ||
| body: input.body, | ||
| ...inputInit | ||
| }; | ||
| } else { | ||
| url = new URL(input); | ||
| init = inputInit; | ||
| } | ||
| init = { | ||
| duplex: "half", | ||
| redirect: "manual", | ||
| ...init | ||
| }; | ||
| let res; | ||
| if (addr.socketPath) { | ||
| url.protocol = "http:"; | ||
| res = await fetch(url, { | ||
| ...init, | ||
| ...fetchSocketOptions(addr.socketPath) | ||
| }); | ||
| } else { | ||
| const origin = `http://${addr.host}${addr.port ? `:${addr.port}` : ""}`; | ||
| const outURL = new URL(url.pathname + url.search, origin); | ||
| res = await fetch(outURL, init); | ||
| } | ||
| const headers = new Headers(res.headers); | ||
| headers.delete("transfer-encoding"); | ||
| return new Response(res.body, { | ||
| status: res.status, | ||
| statusText: res.statusText, | ||
| headers | ||
| }); | ||
| } | ||
| function fetchSocketOptions(socketPath) { | ||
| if ("Bun" in globalThis) return { unix: socketPath }; | ||
| if ("Deno" in globalThis) return { client: Deno.createHttpClient({ | ||
| transport: "unix", | ||
| path: socketPath | ||
| }) }; | ||
| return { dispatcher: new Agent({ connect: { socketPath } }) }; | ||
| } | ||
| //#endregion | ||
| //#region src/runner/node.ts | ||
| var NodeEnvRunner = class { | ||
| closed = false; | ||
| #name; | ||
| #entry; | ||
| #data; | ||
| #hooks; | ||
| #worker; | ||
| #address; | ||
| #proxy; | ||
| #messageListeners; | ||
| constructor(opts) { | ||
| this.#name = opts.name; | ||
| this.#entry = opts.entry; | ||
| this.#data = opts.data; | ||
| this.#hooks = opts.hooks || {}; | ||
| this.#proxy = createHTTPProxy(); | ||
| this.#messageListeners = /* @__PURE__ */ new Set(); | ||
| this.#initWorker(); | ||
| } | ||
| get ready() { | ||
| return Boolean(!this.closed && this.#address && this.#proxy && this.#worker); | ||
| } | ||
| async fetch(input, init) { | ||
| for (let i = 0; i < 5 && !(this.#address && this.#proxy); i++) await new Promise((r) => setTimeout(r, 100 * Math.pow(2, i))); | ||
| if (!(this.#address && this.#proxy)) return new Response("Node env runner worker is unavailable", { status: 503 }); | ||
| return fetchAddress(this.#address, input, init); | ||
| } | ||
| upgrade(req, socket, head) { | ||
| if (!this.ready) return; | ||
| return this.#proxy.proxy.ws(req, socket, { | ||
| target: this.#address, | ||
| xfwd: true | ||
| }, head).catch((error) => { | ||
| consola$1.error("WebSocket proxy error:", error); | ||
| }); | ||
| } | ||
| sendMessage(message) { | ||
| if (!this.#worker) throw new Error("Node env worker should be initialized before sending messages."); | ||
| this.#worker.postMessage(message); | ||
| } | ||
| onMessage(listener) { | ||
| this.#messageListeners.add(listener); | ||
| } | ||
| offMessage(listener) { | ||
| this.#messageListeners.delete(listener); | ||
| } | ||
| async close(cause) { | ||
| if (this.closed) return; | ||
| this.closed = true; | ||
| this.#hooks.onClose?.(this, cause); | ||
| this.#hooks = {}; | ||
| const onError = (error) => consola$1.error(error); | ||
| await this.#closeWorker().catch(onError); | ||
| await this.#closeProxy().catch(onError); | ||
| await this.#closeSocket().catch(onError); | ||
| } | ||
| [Symbol.for("nodejs.util.inspect.custom")]() { | ||
| const status = this.closed ? "closed" : this.ready ? "ready" : "pending"; | ||
| return `NodeEnvRunner#${this.#name}(${status})`; | ||
| } | ||
| #initWorker() { | ||
| if (!existsSync(this.#entry)) { | ||
| this.close(`worker entry not found in "${this.#entry}".`); | ||
| return; | ||
| } | ||
| const worker = new Worker(this.#entry, { | ||
| env: { ...process.env }, | ||
| workerData: { | ||
| name: this.#name, | ||
| ...this.#data | ||
| } | ||
| }); | ||
| worker.once("exit", (code) => { | ||
| worker._exitCode = code; | ||
| this.close(`worker exited with code ${code}`); | ||
| }); | ||
| worker.once("error", (error) => { | ||
| consola$1.error(`Worker error:`, error); | ||
| this.close(error); | ||
| }); | ||
| worker.on("message", (message) => { | ||
| if (message?.address) { | ||
| this.#address = message.address; | ||
| this.#hooks.onReady?.(this, this.#address); | ||
| } | ||
| for (const listener of this.#messageListeners) listener(message); | ||
| }); | ||
| this.#worker = worker; | ||
| } | ||
| async #closeProxy() { | ||
| this.#proxy?.proxy?.close(() => {}); | ||
| this.#proxy = void 0; | ||
| } | ||
| async #closeSocket() { | ||
| const socketPath = this.#address?.socketPath; | ||
| if (socketPath && socketPath[0] !== "\0" && !socketPath.startsWith(String.raw`\\.\pipe`)) await rm(socketPath).catch(() => {}); | ||
| this.#address = void 0; | ||
| } | ||
| async #closeWorker() { | ||
| if (!this.#worker) return; | ||
| this.#worker.postMessage({ event: "shutdown" }); | ||
| if (!this.#worker._exitCode && !a && !T) await new Promise((resolve$2) => { | ||
| const gracefulShutdownTimeoutMs = Number.parseInt(process.env.NITRO_SHUTDOWN_TIMEOUT || "", 10) || 5e3; | ||
| const timeout = setTimeout(() => { | ||
| consola$1.warn(`force closing node env runner worker...`); | ||
| resolve$2(); | ||
| }, gracefulShutdownTimeoutMs); | ||
| this.#worker?.on("message", (message) => { | ||
| if (message.event === "exit") { | ||
| clearTimeout(timeout); | ||
| resolve$2(); | ||
| } | ||
| }); | ||
| }); | ||
| this.#worker.removeAllListeners(); | ||
| await this.#worker.terminate().catch((error) => { | ||
| consola$1.error(error); | ||
| }); | ||
| this.#worker = void 0; | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/dev/vfs.ts | ||
| function createVFSHandler(nitro) { | ||
| return defineHandler(async (event) => { | ||
| const { socket } = event.runtime?.node?.req || {}; | ||
| const ip = getRequestIP(event, { xForwardedFor: !socket?.remoteAddress && !socket?.localAddress && Object.keys(socket?.address?.() || {}).length === 0 && socket?.readable && socket?.writable && !socket?.remotePort }); | ||
| if (!(ip && /^::1$|^127\.\d+\.\d+\.\d+$/.test(ip))) throw new HTTPError({ | ||
| statusText: `Forbidden IP: "${ip || "?"}"`, | ||
| status: 403 | ||
| }); | ||
| const url = event.context.params?._ || ""; | ||
| const isJson = url.endsWith(".json") || event.req.headers.get("accept")?.includes("application/json"); | ||
| const id = decodeURIComponent(url.replace(/^(\.json)?\/?/, "") || ""); | ||
| if (id && !nitro.vfs.has(id)) throw new HTTPError({ | ||
| message: "File not found", | ||
| status: 404 | ||
| }); | ||
| const content = id ? await nitro.vfs.get(id)?.render() : void 0; | ||
| if (isJson) return { | ||
| rootDir: nitro.options.rootDir, | ||
| entries: [...nitro.vfs.keys()].map((id$1) => ({ | ||
| id: id$1, | ||
| path: "/_vfs.json/" + encodeURIComponent(id$1) | ||
| })), | ||
| current: id ? { | ||
| id, | ||
| content | ||
| } : null | ||
| }; | ||
| const directories = { [nitro.options.rootDir]: {} }; | ||
| const fpaths = [...nitro.vfs.keys()]; | ||
| for (const item of fpaths) { | ||
| const segments = item.replace(nitro.options.rootDir, "").split("/").filter(Boolean); | ||
| let currentDir = item.startsWith(nitro.options.rootDir) ? directories[nitro.options.rootDir] : directories; | ||
| for (const segment of segments) { | ||
| if (!currentDir[segment]) currentDir[segment] = {}; | ||
| currentDir = currentDir[segment]; | ||
| } | ||
| } | ||
| const generateHTML = (directory, path$1 = []) => Object.entries(directory).map(([fname, value = {}]) => { | ||
| const subpath = [...path$1, fname]; | ||
| const key = subpath.join("/"); | ||
| const encodedUrl = encodeURIComponent(key); | ||
| const linkClass = url === `/${encodedUrl}` ? "bg-gray-700 text-white" : "hover:bg-gray-800 text-gray-200"; | ||
| return Object.keys(value).length === 0 ? ` | ||
| <li class="flex flex-nowrap"> | ||
| <a href="/_vfs/${encodedUrl}" class="w-full text-sm px-2 py-1 border-b border-gray-10 ${linkClass}"> | ||
| ${fname} | ||
| </a> | ||
| </li> | ||
| ` : ` | ||
| <li> | ||
| <details ${url.startsWith(`/${encodedUrl}`) ? "open" : ""}> | ||
| <summary class="w-full text-sm px-2 py-1 border-b border-gray-10 hover:bg-gray-800 text-gray-200"> | ||
| ${fname} | ||
| </summary> | ||
| <ul class="ml-4"> | ||
| ${generateHTML(value, subpath)} | ||
| </ul> | ||
| </details> | ||
| </li> | ||
| `; | ||
| }).join(""); | ||
| const rootDirectory = directories[nitro.options.rootDir]; | ||
| delete directories[nitro.options.rootDir]; | ||
| const files = ` | ||
| <div class="h-full overflow-auto border-r border-gray:10"> | ||
| <p class="text-white text-bold text-center py-1 opacity-50">Virtual Files</p> | ||
| <ul class="flex flex-col">${generateHTML(rootDirectory, [nitro.options.rootDir]) + generateHTML(directories)}</ul> | ||
| </div> | ||
| `; | ||
| const file = id ? editorTemplate({ | ||
| readOnly: true, | ||
| language: id.endsWith("html") ? "html" : "javascript", | ||
| theme: "vs-dark", | ||
| value: content, | ||
| wordWrap: "wordWrapColumn", | ||
| wordWrapColumn: 80 | ||
| }) : ` | ||
| <div class="w-full h-full flex opacity-50"> | ||
| <h1 class="text-white m-auto">Select a virtual file to inspect</h1> | ||
| </div> | ||
| `; | ||
| event.res.headers.set("Content-Type", "text/html; charset=utf-8"); | ||
| return ` | ||
| <!doctype html> | ||
| <html> | ||
| <head> | ||
| <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@unocss/reset/tailwind.min.css" /> | ||
| <link rel="stylesheet" data-name="vs/editor/editor.main" href="${vsUrl}/editor/editor.main.min.css"> | ||
| <script src="https://cdn.jsdelivr.net/npm/@unocss/runtime"><\/script> | ||
| <style> | ||
| html { | ||
| background: #1E1E1E; | ||
| color: white; | ||
| } | ||
| [un-cloak] { | ||
| display: none; | ||
| } | ||
| </style> | ||
| </head> | ||
| <body class="bg-[#1E1E1E]"> | ||
| <div un-cloak class="h-screen grid grid-cols-[300px_1fr]"> | ||
| ${files} | ||
| ${file} | ||
| </div> | ||
| </body> | ||
| </html>`; | ||
| }); | ||
| } | ||
| const monacoUrl = `https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.30.0/min`; | ||
| const vsUrl = `${monacoUrl}/vs`; | ||
| const editorTemplate = (options) => ` | ||
| <div id="editor" class="min-h-screen w-full h-full"></div> | ||
| <script src="${vsUrl}/loader.min.js"><\/script> | ||
| <script> | ||
| require.config({ paths: { vs: '${vsUrl}' } }) | ||
| const proxy = URL.createObjectURL(new Blob([\` | ||
| self.MonacoEnvironment = { baseUrl: '${monacoUrl}' } | ||
| importScripts('${vsUrl}/base/worker/workerMain.min.js') | ||
| \`], { type: 'text/javascript' })) | ||
| window.MonacoEnvironment = { getWorkerUrl: () => proxy } | ||
| setTimeout(() => { | ||
| require(['vs/editor/editor.main'], function () { | ||
| monaco.editor.create(document.getElementById('editor'), ${JSON.stringify(options)}) | ||
| }) | ||
| }, 0); | ||
| <\/script> | ||
| `; | ||
| //#endregion | ||
| //#region src/runtime/internal/error/utils.ts | ||
| function defineNitroErrorHandler(handler) { | ||
| return handler; | ||
| } | ||
| //#endregion | ||
| //#region src/runtime/internal/error/dev.ts | ||
| var dev_default = defineNitroErrorHandler(async function defaultNitroErrorHandler(error, event) { | ||
| const res = await defaultHandler(error, event); | ||
| return new FastResponse(typeof res.body === "string" ? res.body : JSON.stringify(res.body, null, 2), res); | ||
| }); | ||
| async function defaultHandler(error, event, opts) { | ||
| const isSensitive = error.unhandled; | ||
| const status = error.status || 500; | ||
| const url = getRequestURL(event, { | ||
| xForwardedHost: true, | ||
| xForwardedProto: true | ||
| }); | ||
| if (status === 404) { | ||
| const baseURL = import.meta.baseURL || "/"; | ||
| if (/^\/[^/]/.test(baseURL) && !url.pathname.startsWith(baseURL)) return { | ||
| status: 302, | ||
| statusText: "Found", | ||
| headers: { location: `${baseURL}${url.pathname.slice(1)}${url.search}` }, | ||
| body: `Redirecting...` | ||
| }; | ||
| } | ||
| await loadStackTrace(error).catch(consola$1.error); | ||
| const youch = new Youch(); | ||
| if (isSensitive && !opts?.silent) { | ||
| const tags = [error.unhandled && "[unhandled]"].filter(Boolean).join(" "); | ||
| const ansiError = await (await youch.toANSI(error)).replaceAll(process.cwd(), "."); | ||
| consola$1.error(`[request error] ${tags} [${event.req.method}] ${url}\n\n`, ansiError); | ||
| } | ||
| const useJSON = opts?.json ?? !event.req.headers.get("accept")?.includes("text/html"); | ||
| const headers = { | ||
| "content-type": useJSON ? "application/json" : "text/html", | ||
| "x-content-type-options": "nosniff", | ||
| "x-frame-options": "DENY", | ||
| "referrer-policy": "no-referrer", | ||
| "content-security-policy": "script-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self';" | ||
| }; | ||
| if (status === 404 || !event.res.headers.has("cache-control")) headers["cache-control"] = "no-cache"; | ||
| const body = useJSON ? { | ||
| error: true, | ||
| url, | ||
| status, | ||
| statusText: error.statusText, | ||
| message: error.message, | ||
| data: error.data, | ||
| stack: error.stack?.split("\n").map((line) => line.trim()) | ||
| } : await youch.toHTML(error, { request: { | ||
| url: url.href, | ||
| method: event.req.method, | ||
| headers: Object.fromEntries(event.req.headers.entries()) | ||
| } }); | ||
| return { | ||
| status, | ||
| statusText: error.statusText, | ||
| headers, | ||
| body | ||
| }; | ||
| } | ||
| async function loadStackTrace(error) { | ||
| if (!(error instanceof Error)) return; | ||
| const parsed = await new ErrorParser().defineSourceLoader(sourceLoader).parse(error); | ||
| const stack = error.message + "\n" + parsed.frames.map((frame) => fmtFrame(frame)).join("\n"); | ||
| Object.defineProperty(error, "stack", { value: stack }); | ||
| if (error.cause) await loadStackTrace(error.cause).catch(consola$1.error); | ||
| } | ||
| async function sourceLoader(frame) { | ||
| if (!frame.fileName || frame.fileType !== "fs" || frame.type === "native") return; | ||
| if (frame.type === "app") { | ||
| const rawSourceMap = await readFile(`${frame.fileName}.map`, "utf8").catch(() => {}); | ||
| if (rawSourceMap) { | ||
| const originalPosition = (await new SourceMapConsumer(rawSourceMap)).originalPositionFor({ | ||
| line: frame.lineNumber, | ||
| column: frame.columnNumber | ||
| }); | ||
| if (originalPosition.source && originalPosition.line) { | ||
| frame.fileName = resolve(dirname(frame.fileName), originalPosition.source); | ||
| frame.lineNumber = originalPosition.line; | ||
| frame.columnNumber = originalPosition.column || 0; | ||
| } | ||
| } | ||
| } | ||
| const contents = await readFile(frame.fileName, "utf8").catch(() => {}); | ||
| return contents ? { contents } : void 0; | ||
| } | ||
| function fmtFrame(frame) { | ||
| if (frame.type === "native") return frame.raw; | ||
| const src = `${frame.fileName || ""}:${frame.lineNumber}:${frame.columnNumber})`; | ||
| return frame.functionName ? `at ${frame.functionName} (${src}` : `at ${src}`; | ||
| } | ||
| //#endregion | ||
| //#region src/dev/app.ts | ||
| var NitroDevApp = class { | ||
| nitro; | ||
| fetch; | ||
| constructor(nitro, catchAllHandler) { | ||
| this.nitro = nitro; | ||
| const app = this.#createApp(catchAllHandler); | ||
| this.fetch = app.fetch.bind(app); | ||
| } | ||
| #createApp(catchAllHandler) { | ||
| const app = new H3({ | ||
| debug: true, | ||
| onError: async (error, event) => { | ||
| const errorHandler = this.nitro.options.devErrorHandler || dev_default; | ||
| await loadStackTrace(error).catch(() => {}); | ||
| return errorHandler(error, event, { defaultHandler }); | ||
| } | ||
| }); | ||
| for (const h of this.nitro.options.devHandlers) { | ||
| const handler = toEventHandler(h.handler); | ||
| if (!handler) { | ||
| this.nitro.logger.warn("Invalid dev handler:", h); | ||
| continue; | ||
| } | ||
| if (h.middleware || !h.route) if (h.route) app.use(h.route, handler, { method: h.method }); | ||
| else app.use(handler, { method: h.method }); | ||
| else app.on(h.method || "", h.route, handler, { meta: h.meta }); | ||
| } | ||
| app.get("/_vfs/**", createVFSHandler(this.nitro)); | ||
| for (const asset of this.nitro.options.publicAssets) { | ||
| const assetBase = joinURL(this.nitro.options.baseURL, asset.baseURL || "/"); | ||
| app.use(joinURL(assetBase, "**"), (event) => serveStaticDir(event, { | ||
| dir: asset.dir, | ||
| base: assetBase, | ||
| fallthrough: asset.fallthrough | ||
| })); | ||
| } | ||
| const routes = Object.keys(this.nitro.options.devProxy).sort().reverse(); | ||
| for (const route of routes) { | ||
| let opts = this.nitro.options.devProxy[route]; | ||
| if (typeof opts === "string") opts = { target: opts }; | ||
| const proxy = createHTTPProxy(opts); | ||
| app.all(route, proxy.handleEvent); | ||
| } | ||
| if (catchAllHandler) app.all("/**", catchAllHandler); | ||
| return app; | ||
| } | ||
| }; | ||
| function serveStaticDir(event, opts) { | ||
| const dir = resolve$1(opts.dir) + "/"; | ||
| const r = (id) => { | ||
| if (!id.startsWith(opts.base) || !extname$1(id)) return; | ||
| const resolved = join$1(dir, id.slice(opts.base.length)); | ||
| if (resolved.startsWith(dir)) return resolved; | ||
| }; | ||
| return serveStatic(event, { | ||
| fallthrough: opts.fallthrough, | ||
| getMeta: async (id) => { | ||
| const path$1 = r(id); | ||
| if (!path$1) return; | ||
| const s = await stat$1(path$1).catch(() => null); | ||
| if (!s?.isFile()) return; | ||
| const ext = extname$1(path$1); | ||
| return { | ||
| size: s.size, | ||
| mtime: s.mtime, | ||
| type: src_default.getType(ext) || "application/octet-stream" | ||
| }; | ||
| }, | ||
| getContents(id) { | ||
| const path$1 = r(id); | ||
| if (!path$1) return; | ||
| const stream = createReadStream(path$1); | ||
| const acceptEncoding = event.req.headers.get("accept-encoding") || ""; | ||
| if (acceptEncoding.includes("br")) { | ||
| event.res.headers.set("Content-Encoding", "br"); | ||
| event.res.headers.delete("Content-Length"); | ||
| event.res.headers.set("Vary", "Accept-Encoding"); | ||
| return stream.pipe(createBrotliCompress()); | ||
| } else if (acceptEncoding.includes("gzip")) { | ||
| event.res.headers.set("Content-Encoding", "gzip"); | ||
| event.res.headers.delete("Content-Length"); | ||
| event.res.headers.set("Vary", "Accept-Encoding"); | ||
| return stream.pipe(createGzip()); | ||
| } | ||
| return stream; | ||
| } | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region src/dev/server.ts | ||
| function createDevServer(nitro) { | ||
| return new NitroDevServer(nitro); | ||
| } | ||
| var NitroDevServer = class NitroDevServer extends NitroDevApp { | ||
| #entry; | ||
| #workerData = {}; | ||
| #listeners = []; | ||
| #watcher; | ||
| #workers = []; | ||
| #workerIdCtr = 0; | ||
| #workerError; | ||
| #building = true; | ||
| #buildError; | ||
| #messageListeners = /* @__PURE__ */ new Set(); | ||
| constructor(nitro) { | ||
| super(nitro, async (event) => { | ||
| const worker = await this.#getWorker(); | ||
| if (!worker) return this.#generateError(); | ||
| return worker.fetch(event.req); | ||
| }); | ||
| for (const key of Object.getOwnPropertyNames(NitroDevServer.prototype)) { | ||
| const value = this[key]; | ||
| if (typeof value === "function" && key !== "constructor") this[key] = value.bind(this); | ||
| } | ||
| nitro.fetch = this.fetch.bind(this); | ||
| this.#entry = resolve$1(nitro.options.output.dir, nitro.options.output.serverDir, "index.mjs"); | ||
| nitro.hooks.hook("close", () => this.close()); | ||
| nitro.hooks.hook("dev:start", () => { | ||
| this.#building = true; | ||
| this.#buildError = void 0; | ||
| }); | ||
| nitro.hooks.hook("dev:reload", (payload) => { | ||
| this.#buildError = void 0; | ||
| this.#building = false; | ||
| if (payload?.entry) this.#entry = payload.entry; | ||
| if (payload?.workerData) this.#workerData = payload.workerData; | ||
| this.reload(); | ||
| }); | ||
| nitro.hooks.hook("dev:error", (cause) => { | ||
| this.#buildError = cause; | ||
| this.#building = false; | ||
| for (const worker of this.#workers) worker.close(); | ||
| }); | ||
| const devWatch = nitro.options.devServer.watch; | ||
| if (devWatch && devWatch.length > 0) { | ||
| const debouncedReload = debounce(() => this.reload()); | ||
| this.#watcher = watch$1(devWatch, nitro.options.watchOptions); | ||
| this.#watcher.on("add", debouncedReload).on("change", debouncedReload); | ||
| } | ||
| } | ||
| async upgrade(req, socket, head) { | ||
| const worker = await this.#getWorker(); | ||
| if (!worker) throw new HTTPError({ | ||
| status: 503, | ||
| statusText: "No worker available." | ||
| }); | ||
| if (!worker.upgrade) throw new HTTPError({ | ||
| status: 501, | ||
| statusText: "Worker does not support upgrades." | ||
| }); | ||
| return worker.upgrade(req, socket, head); | ||
| } | ||
| listen(opts) { | ||
| const server = serve({ | ||
| ...opts, | ||
| fetch: this.fetch, | ||
| gracefulShutdown: false | ||
| }); | ||
| this.#listeners.push(server); | ||
| if (server.node?.server) server.node.server.on("upgrade", (req, sock, head) => this.upgrade(req, sock, head)); | ||
| return server; | ||
| } | ||
| async close() { | ||
| await Promise.all([ | ||
| Promise.all(this.#listeners.map((l) => l.close())).then(() => { | ||
| this.#listeners = []; | ||
| }), | ||
| Promise.all(this.#workers.map((w) => w.close())).then(() => { | ||
| this.#workers = []; | ||
| }), | ||
| Promise.resolve(this.#watcher?.close()).then(() => { | ||
| this.#watcher = void 0; | ||
| }) | ||
| ].map((p) => p.catch((error) => { | ||
| consola$1.error(error); | ||
| }))); | ||
| } | ||
| reload() { | ||
| for (const worker$1 of this.#workers) worker$1.close(); | ||
| const worker = new NodeEnvRunner({ | ||
| name: `Nitro_${this.#workerIdCtr++}`, | ||
| entry: this.#entry, | ||
| data: this.#workerData, | ||
| hooks: { | ||
| onClose: (worker$1, cause) => { | ||
| this.#workerError = cause; | ||
| const index = this.#workers.indexOf(worker$1); | ||
| if (index !== -1) this.#workers.splice(index, 1); | ||
| }, | ||
| onReady: async (_worker, addr) => { | ||
| writeDevBuildInfo(this.nitro, addr).catch(() => {}); | ||
| } | ||
| } | ||
| }); | ||
| if (!worker.closed) { | ||
| for (const listener of this.#messageListeners) worker.onMessage(listener); | ||
| this.#workers.unshift(worker); | ||
| } | ||
| } | ||
| sendMessage(message) { | ||
| for (const worker of this.#workers) if (!worker.closed) worker.sendMessage(message); | ||
| } | ||
| onMessage(listener) { | ||
| this.#messageListeners.add(listener); | ||
| for (const worker of this.#workers) worker.onMessage(listener); | ||
| } | ||
| offMessage(listener) { | ||
| this.#messageListeners.delete(listener); | ||
| for (const worker of this.#workers) worker.offMessage(listener); | ||
| } | ||
| async #getWorker() { | ||
| let retry = 0; | ||
| const maxRetries = a || T ? 100 : 10; | ||
| while (this.#building || ++retry < maxRetries) { | ||
| if ((this.#workers.length === 0 || this.#buildError) && !this.#building) return; | ||
| const activeWorker = this.#workers.find((w) => w.ready); | ||
| if (activeWorker) return activeWorker; | ||
| await new Promise((resolve$2) => setTimeout(resolve$2, 600)); | ||
| } | ||
| } | ||
| #generateError() { | ||
| const error = this.#buildError || this.#workerError; | ||
| if (error) { | ||
| try { | ||
| error.unhandled = false; | ||
| let id = error.id || error.path; | ||
| if (id) { | ||
| const cause = error.errors?.[0]; | ||
| const loc = error.location || error.loc || cause?.location || cause?.loc; | ||
| if (loc) id += `:${loc.line}:${loc.column}`; | ||
| error.stack = (error.stack || "").replace(/(^\s*at\s+.+)/m, ` at ${id}\n$1`); | ||
| } | ||
| } catch {} | ||
| return new HTTPError(error); | ||
| } | ||
| return new Response(JSON.stringify({ | ||
| error: "Dev server is unavailable.", | ||
| hint: "Please reload the page and check the console for errors if the issue persists." | ||
| }, null, 2), { | ||
| status: 503, | ||
| statusText: "Dev server is unavailable", | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| "Cache-Control": "no-store", | ||
| Refresh: "3" | ||
| } | ||
| }); | ||
| } | ||
| }; | ||
| //#endregion | ||
| export { NodeEnvRunner as i, createDevServer as n, NitroDevApp as r, NitroDevServer as t }; |
| import { $ as resolveModulePath, A as compressPublicAssets, H as d, I as prettyPath, L as resolveNitroPath, M as build, R as writeFile$1, V as a, at as join, ct as resolve, et as resolveModuleURL, j as src_default, k as scanUnprefixedPublicAssets, p as runParallel, q as findWorkspaceDir, st as relative } from "../_build/common.mjs"; | ||
| import { n as loadConfig, r as watchConfig } from "../_libs/rc9+c12+dotenv.mjs"; | ||
| import { n as resolveCompatibilityDates, r as resolveCompatibilityDatesFromEnv } from "../_libs/compatx.mjs"; | ||
| import { t as klona } from "../_libs/klona.mjs"; | ||
| import { t as escapeStringRegexp } from "../_libs/escape-string-regexp.mjs"; | ||
| import { n as parse, t as TSConfckCache } from "../_libs/tsconfck.mjs"; | ||
| import { n as scanHandlers, t as scanAndSyncOptions } from "./nitro2.mjs"; | ||
| import { a as findRoute, i as findAllRoutes, n as addRoute, r as createRouter, t as compileRouterToString } from "../_libs/rou3.mjs"; | ||
| import { n as z, t as P } from "../_libs/ultrahtml.mjs"; | ||
| import { createRequire } from "node:module"; | ||
| import consola$1, { consola } from "consola"; | ||
| import { Hookable, createDebugger } from "hookable"; | ||
| import { existsSync } from "node:fs"; | ||
| import { readFile } from "node:fs/promises"; | ||
| import { pathToFileURL } from "node:url"; | ||
| import { defu } from "defu"; | ||
| import { joinURL, parseURL, withBase, withLeadingSlash, withQuery, withTrailingSlash, withoutBase, withoutTrailingSlash } from "ufo"; | ||
| import { runtimeDir } from "nitro/meta"; | ||
| import { colors } from "consola/utils"; | ||
| import { hash } from "ohash"; | ||
| import http from "node:http"; | ||
| import { toRequest } from "h3"; | ||
| //#region src/config/defaults.ts | ||
| const NitroDefaults = { | ||
| compatibilityDate: "latest", | ||
| debug: d, | ||
| logLevel: a ? 1 : 3, | ||
| runtimeConfig: { | ||
| app: {}, | ||
| nitro: {} | ||
| }, | ||
| serverDir: false, | ||
| scanDirs: [], | ||
| buildDir: `node_modules/.nitro`, | ||
| output: { | ||
| dir: "{{ rootDir }}/.output", | ||
| serverDir: "{{ output.dir }}/server", | ||
| publicDir: "{{ output.dir }}/public" | ||
| }, | ||
| features: {}, | ||
| experimental: {}, | ||
| future: {}, | ||
| storage: {}, | ||
| devStorage: {}, | ||
| publicAssets: [], | ||
| serverAssets: [], | ||
| plugins: [], | ||
| tasks: {}, | ||
| scheduledTasks: {}, | ||
| imports: false, | ||
| virtual: {}, | ||
| compressPublicAssets: false, | ||
| ignore: [], | ||
| wasm: {}, | ||
| dev: false, | ||
| devServer: { watch: [] }, | ||
| watchOptions: { ignoreInitial: true }, | ||
| devProxy: {}, | ||
| logging: { | ||
| compressedSizes: true, | ||
| buildSuccess: true | ||
| }, | ||
| baseURL: process.env.NITRO_APP_BASE_URL || "/", | ||
| handlers: [], | ||
| devHandlers: [], | ||
| errorHandler: void 0, | ||
| routes: {}, | ||
| routeRules: {}, | ||
| prerender: { | ||
| autoSubfolderIndex: true, | ||
| concurrency: 1, | ||
| interval: 0, | ||
| retry: 3, | ||
| retryDelay: 500, | ||
| failOnError: false, | ||
| crawlLinks: false, | ||
| ignore: [], | ||
| routes: [] | ||
| }, | ||
| builder: void 0, | ||
| moduleSideEffects: ["unenv/polyfill/"], | ||
| replace: {}, | ||
| node: true, | ||
| sourcemap: false, | ||
| traceDeps: [], | ||
| typescript: { | ||
| strict: true, | ||
| generateRuntimeConfigTypes: false, | ||
| generateTsConfig: false, | ||
| tsconfigPath: "tsconfig.json", | ||
| tsConfig: void 0 | ||
| }, | ||
| hooks: {}, | ||
| commands: {}, | ||
| framework: { | ||
| name: "nitro", | ||
| version: "" | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/config/resolvers/assets.ts | ||
| async function resolveAssetsOptions(options) { | ||
| for (const publicAsset of options.publicAssets) { | ||
| publicAsset.dir = resolve(options.rootDir, publicAsset.dir); | ||
| publicAsset.baseURL = withLeadingSlash(withoutTrailingSlash(publicAsset.baseURL || "/")); | ||
| } | ||
| for (const dir of [options.rootDir, ...options.scanDirs]) { | ||
| const publicDir = resolve(dir, "public"); | ||
| if (!existsSync(publicDir)) continue; | ||
| if (options.publicAssets.some((asset) => asset.dir === publicDir)) continue; | ||
| options.publicAssets.push({ dir: publicDir }); | ||
| } | ||
| for (const serverAsset of options.serverAssets) serverAsset.dir = resolve(options.rootDir, serverAsset.dir); | ||
| options.serverAssets.push({ | ||
| baseName: "server", | ||
| dir: resolve(options.rootDir, "assets") | ||
| }); | ||
| for (const asset of options.publicAssets) { | ||
| asset.baseURL = asset.baseURL || "/"; | ||
| const isTopLevel = asset.baseURL === "/"; | ||
| asset.fallthrough = asset.fallthrough ?? isTopLevel; | ||
| const routeRule = options.routeRules[asset.baseURL + "/**"]; | ||
| asset.maxAge = (routeRule?.cache)?.maxAge ?? asset.maxAge ?? 0; | ||
| if (asset.maxAge && !asset.fallthrough) options.routeRules[asset.baseURL + "/**"] = defu(routeRule, { headers: { "cache-control": `public, max-age=${asset.maxAge}, immutable` } }); | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/compatibility.ts | ||
| async function resolveCompatibilityOptions(options) { | ||
| options.compatibilityDate = resolveCompatibilityDatesFromEnv(options.compatibilityDate); | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/database.ts | ||
| async function resolveDatabaseOptions(options) { | ||
| if (options.experimental.database && options.imports) { | ||
| options.imports.presets ??= []; | ||
| options.imports.presets.push({ | ||
| from: "nitro/database", | ||
| imports: ["useDatabase"] | ||
| }); | ||
| if (options.dev && !options.database && !options.devDatabase) options.devDatabase = { default: { | ||
| connector: "sqlite", | ||
| options: { cwd: options.rootDir } | ||
| } }; | ||
| else if (options.node && !options.database) options.database = { default: { | ||
| connector: "sqlite", | ||
| options: {} | ||
| } }; | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/export-conditions.ts | ||
| async function resolveExportConditionsOptions(options) { | ||
| options.exportConditions = _resolveExportConditions(options.exportConditions || [], { | ||
| dev: options.dev, | ||
| node: options.node, | ||
| wasm: options.wasm !== false | ||
| }); | ||
| } | ||
| function _resolveExportConditions(conditions, opts) { | ||
| const resolvedConditions = []; | ||
| resolvedConditions.push(opts.dev ? "development" : "production"); | ||
| resolvedConditions.push(...conditions); | ||
| if (opts.node) resolvedConditions.push("node"); | ||
| else resolvedConditions.push("wintercg", "worker", "web", "browser", "workerd", "edge-light", "netlify", "edge-routine", "deno"); | ||
| if (opts.wasm) resolvedConditions.push("wasm", "unwasm"); | ||
| resolvedConditions.push("import", "default", "module"); | ||
| if ("Bun" in globalThis) resolvedConditions.push("bun"); | ||
| else if ("Deno" in globalThis) resolvedConditions.push("deno"); | ||
| return resolvedConditions.filter((c, i) => resolvedConditions.indexOf(c) === i); | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/imports.ts | ||
| async function resolveImportsOptions(options) { | ||
| if (options.imports === false) return; | ||
| options.imports.presets ??= []; | ||
| options.imports.dirs ??= []; | ||
| options.imports.dirs.push(...options.scanDirs.map((dir) => join(dir, "utils/**/*"))); | ||
| if (Array.isArray(options.imports.exclude) && options.imports.exclude.length === 0) { | ||
| options.imports.exclude.push(/[/\\]\.git[/\\]/); | ||
| options.imports.exclude.push(options.buildDir); | ||
| const scanDirsInNodeModules = options.scanDirs.map((dir) => dir.match(/(?<=\/)node_modules\/(.+)$/)?.[1]).filter(Boolean); | ||
| options.imports.exclude.push(scanDirsInNodeModules.length > 0 ? /* @__PURE__ */ new RegExp(`node_modules\\/(?!${scanDirsInNodeModules.map((dir) => escapeStringRegexp(dir)).join("|")})`) : /[/\\]node_modules[/\\]/); | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/open-api.ts | ||
| async function resolveOpenAPIOptions(options) { | ||
| if (!options.experimental.openAPI) return; | ||
| if (!options.dev && !options.openAPI?.production) return; | ||
| const shouldPrerender = !options.dev && options.openAPI?.production === "prerender"; | ||
| const handlersEnv = shouldPrerender ? "prerender" : ""; | ||
| const prerenderRoutes = []; | ||
| const jsonRoute = options.openAPI?.route || "/_openapi.json"; | ||
| prerenderRoutes.push(jsonRoute); | ||
| options.handlers.push({ | ||
| route: jsonRoute, | ||
| env: handlersEnv, | ||
| handler: join(runtimeDir, "internal/routes/openapi") | ||
| }); | ||
| if (options.openAPI?.ui?.scalar !== false) { | ||
| const scalarRoute = options.openAPI?.ui?.scalar?.route || "/_scalar"; | ||
| prerenderRoutes.push(scalarRoute); | ||
| options.handlers.push({ | ||
| route: options.openAPI?.ui?.scalar?.route || "/_scalar", | ||
| env: handlersEnv, | ||
| handler: join(runtimeDir, "internal/routes/scalar") | ||
| }); | ||
| } | ||
| if (options.openAPI?.ui?.swagger !== false) { | ||
| const swaggerRoute = options.openAPI?.ui?.swagger?.route || "/_swagger"; | ||
| prerenderRoutes.push(swaggerRoute); | ||
| options.handlers.push({ | ||
| route: swaggerRoute, | ||
| env: handlersEnv, | ||
| handler: join(runtimeDir, "internal/routes/swagger") | ||
| }); | ||
| } | ||
| if (shouldPrerender) { | ||
| options.prerender ??= {}; | ||
| options.prerender.routes ??= []; | ||
| options.prerender.routes.push(...prerenderRoutes); | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/tsconfig.ts | ||
| async function resolveTsconfig(options) { | ||
| const root = resolve(options.rootDir || ".") + "/"; | ||
| if (!options.typescript.tsConfig) options.typescript.tsConfig = await loadTsconfig(root); | ||
| if (options.experimental.tsconfigPaths && options.typescript.tsConfig.compilerOptions?.paths) options.alias = { | ||
| ...tsConfigToAliasObj(options.typescript.tsConfig, root), | ||
| ...options.alias | ||
| }; | ||
| } | ||
| async function loadTsconfig(root) { | ||
| const opts = { | ||
| root, | ||
| cache: loadTsconfig["__cache"] ??= new TSConfckCache(), | ||
| ignoreNodeModules: true | ||
| }; | ||
| const tsConfigPath = join(root, "tsconfig.json"); | ||
| const parsed = await parse(tsConfigPath, opts).catch(() => void 0); | ||
| if (!parsed) return {}; | ||
| const { tsconfig, tsconfigFile } = parsed; | ||
| tsconfig.compilerOptions ??= {}; | ||
| if (!tsconfig.compilerOptions.baseUrl) tsconfig.compilerOptions.baseUrl = resolve(tsconfigFile, ".."); | ||
| return tsconfig; | ||
| } | ||
| function tsConfigToAliasObj(tsconfig, root) { | ||
| const compilerOptions = tsconfig?.compilerOptions; | ||
| if (!compilerOptions?.paths) return {}; | ||
| const paths = compilerOptions.paths; | ||
| const alias = {}; | ||
| for (const [key, targets] of Object.entries(paths)) { | ||
| let source = key; | ||
| let target = targets?.[0]; | ||
| if (!target) continue; | ||
| if (source.includes("*") || target.includes("*")) { | ||
| source = source.replace(/\/\*$/, ""); | ||
| target = target.replace(/\/\*$/, ""); | ||
| if (source.includes("*") || target.includes("*")) continue; | ||
| } | ||
| if (target.startsWith(".")) { | ||
| if (!compilerOptions.baseUrl) continue; | ||
| target = resolve(root, compilerOptions.baseUrl, target) + (key.endsWith("*") ? "/" : ""); | ||
| } | ||
| alias[source] = target; | ||
| } | ||
| return alias; | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/paths.ts | ||
| const RESOLVE_EXTENSIONS = [ | ||
| ".ts", | ||
| ".js", | ||
| ".mts", | ||
| ".mjs", | ||
| ".tsx", | ||
| ".jsx" | ||
| ]; | ||
| async function resolvePathOptions(options) { | ||
| options.rootDir = resolve(options.rootDir || ".") + "/"; | ||
| options.buildDir = resolve(options.rootDir, options.buildDir || ".") + "/"; | ||
| options.workspaceDir ||= await findWorkspaceDir(options.rootDir).catch(() => options.rootDir) + "/"; | ||
| if (options.srcDir) { | ||
| if (options.serverDir === void 0) options.serverDir = options.srcDir; | ||
| consola$1.warn(`"srcDir" option is deprecated. Please use "serverDir" instead.`); | ||
| } | ||
| if (options.serverDir !== false) { | ||
| if (options.serverDir === true) options.serverDir = "server"; | ||
| options.serverDir = resolve(options.rootDir, options.serverDir || ".") + "/"; | ||
| } | ||
| options.alias ??= {}; | ||
| if (!options.static && !options.entry) throw new Error(`Nitro entry is missing! Is "${options.preset}" preset correct?`); | ||
| if (options.entry) options.entry = resolveNitroPath(options.entry, options); | ||
| options.output.dir = resolveNitroPath(options.output.dir || NitroDefaults.output.dir, options, options.rootDir) + "/"; | ||
| options.output.publicDir = resolveNitroPath(options.output.publicDir || NitroDefaults.output.publicDir, options, options.rootDir) + "/"; | ||
| options.output.serverDir = resolveNitroPath(options.output.serverDir || NitroDefaults.output.serverDir, options, options.rootDir) + "/"; | ||
| options.plugins = options.plugins.map((p) => resolveNitroPath(p, options)); | ||
| if (options.serverDir) options.scanDirs.unshift(options.serverDir); | ||
| options.scanDirs = options.scanDirs.map((dir) => resolve(options.rootDir, dir)); | ||
| options.scanDirs = [...new Set(options.scanDirs.map((dir) => dir + "/"))]; | ||
| options.handlers = options.handlers.map((h) => { | ||
| return { | ||
| ...h, | ||
| handler: resolveNitroPath(h.handler, options) | ||
| }; | ||
| }); | ||
| options.routes = Object.fromEntries(Object.entries(options.routes).map(([route, h]) => { | ||
| if (typeof h === "string") h = { handler: h }; | ||
| h.handler = resolveNitroPath(h.handler, options); | ||
| return [route, h]; | ||
| })); | ||
| if (options.serverEntry !== false) { | ||
| if (typeof options?.serverEntry === "string") options.serverEntry = { handler: options.serverEntry }; | ||
| if (options.serverEntry?.handler) options.serverEntry.handler = resolveNitroPath(options.serverEntry.handler, options); | ||
| else { | ||
| const detected = resolveModulePath("./server", { | ||
| try: true, | ||
| from: options.rootDir, | ||
| extensions: RESOLVE_EXTENSIONS.flatMap((ext) => [ext, `.node${ext}`]) | ||
| }); | ||
| if (detected) { | ||
| options.serverEntry ??= { handler: "" }; | ||
| options.serverEntry.handler = detected; | ||
| consola$1.info(`Detected \`${prettyPath(detected)}\` as server entry.`); | ||
| } | ||
| } | ||
| if (options.serverEntry?.handler && !options.serverEntry?.format) { | ||
| const isNode = /\.(node)\.\w+$/.test(options.serverEntry.handler); | ||
| options.serverEntry.format = isNode ? "node" : "web"; | ||
| } | ||
| } | ||
| if (options.renderer === false) options.renderer = void 0; | ||
| else { | ||
| if (options.renderer?.handler) options.renderer.handler = resolveModulePath(resolveNitroPath(options.renderer?.handler, options), { | ||
| from: [options.rootDir, ...options.scanDirs], | ||
| extensions: RESOLVE_EXTENSIONS | ||
| }); | ||
| if (options.renderer?.template) options.renderer.template = resolveModulePath(resolveNitroPath(options.renderer?.template, options), { | ||
| from: [options.rootDir, ...options.scanDirs], | ||
| extensions: [".html"] | ||
| }); | ||
| else if (!options.renderer?.handler) { | ||
| const defaultIndex = resolveModulePath("./index.html", { | ||
| from: [options.rootDir, ...options.scanDirs], | ||
| extensions: [".html"], | ||
| try: true | ||
| }); | ||
| if (defaultIndex) { | ||
| options.renderer ??= {}; | ||
| options.renderer.template = defaultIndex; | ||
| consola$1.info(`Using \`${prettyPath(defaultIndex)}\` as renderer template.`); | ||
| } | ||
| } | ||
| if (options.renderer?.template && !options.renderer?.handler) { | ||
| options.renderer ??= {}; | ||
| options.renderer.handler = join(runtimeDir, "internal/routes/renderer-template" + (options.dev ? ".dev" : "")); | ||
| } | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/route-rules.ts | ||
| async function resolveRouteRulesOptions(options) { | ||
| options.routeRules = normalizeRouteRules(options); | ||
| } | ||
| function normalizeRouteRules(config) { | ||
| const normalizedRules = {}; | ||
| for (let path in config.routeRules) { | ||
| const routeConfig = config.routeRules[path]; | ||
| path = withLeadingSlash(path); | ||
| const routeRules = { | ||
| ...routeConfig, | ||
| redirect: void 0, | ||
| proxy: void 0 | ||
| }; | ||
| if (routeConfig.redirect) { | ||
| routeRules.redirect = { | ||
| to: "/", | ||
| status: 307, | ||
| ...typeof routeConfig.redirect === "string" ? { to: routeConfig.redirect } : routeConfig.redirect | ||
| }; | ||
| if (path.endsWith("/**")) routeRules.redirect._redirectStripBase = path.slice(0, -3); | ||
| } | ||
| if (routeConfig.proxy) { | ||
| routeRules.proxy = typeof routeConfig.proxy === "string" ? { to: routeConfig.proxy } : routeConfig.proxy; | ||
| if (path.endsWith("/**")) routeRules.proxy._proxyStripBase = path.slice(0, -3); | ||
| } | ||
| if (routeConfig.cors) routeRules.headers = { | ||
| "access-control-allow-origin": "*", | ||
| "access-control-allow-methods": "*", | ||
| "access-control-allow-headers": "*", | ||
| "access-control-max-age": "0", | ||
| ...routeRules.headers | ||
| }; | ||
| if (routeConfig.swr) { | ||
| routeRules.cache = routeRules.cache || {}; | ||
| routeRules.cache.swr = true; | ||
| if (typeof routeConfig.swr === "number") routeRules.cache.maxAge = routeConfig.swr; | ||
| } | ||
| if (routeConfig.cache === false) routeRules.cache = false; | ||
| normalizedRules[path] = routeRules; | ||
| } | ||
| return normalizedRules; | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/runtime-config.ts | ||
| async function resolveRuntimeConfigOptions(options) { | ||
| options.runtimeConfig = normalizeRuntimeConfig(options); | ||
| } | ||
| function normalizeRuntimeConfig(config) { | ||
| provideFallbackValues(config.runtimeConfig || {}); | ||
| const runtimeConfig = defu(config.runtimeConfig, { | ||
| app: { baseURL: config.baseURL }, | ||
| nitro: { | ||
| envExpansion: config.experimental?.envExpansion, | ||
| openAPI: config.openAPI | ||
| } | ||
| }); | ||
| runtimeConfig.nitro ??= {}; | ||
| runtimeConfig.nitro.routeRules = config.routeRules; | ||
| checkSerializableRuntimeConfig(runtimeConfig); | ||
| return runtimeConfig; | ||
| } | ||
| function provideFallbackValues(obj) { | ||
| for (const key in obj) if (obj[key] === void 0 || obj[key] === null) obj[key] = ""; | ||
| else if (typeof obj[key] === "object") provideFallbackValues(obj[key]); | ||
| } | ||
| function checkSerializableRuntimeConfig(obj, path = []) { | ||
| if (isPrimitiveValue(obj)) return; | ||
| for (const key in obj) { | ||
| const value = obj[key]; | ||
| if (value === null || value === void 0 || isPrimitiveValue(value)) continue; | ||
| if (Array.isArray(value)) for (const [index, item] of value.entries()) checkSerializableRuntimeConfig(item, [...path, `${key}[${index}]`]); | ||
| else if (typeof value === "object" && value.constructor === Object && (!value.constructor?.name || value.constructor.name === "Object")) checkSerializableRuntimeConfig(value, [...path, key]); | ||
| else console.warn(`Runtime config option \`${[...path, key].join(".")}\` may not be able to be serialized.`); | ||
| } | ||
| } | ||
| function isPrimitiveValue(value) { | ||
| return typeof value === "string" || typeof value === "number" || typeof value === "boolean"; | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/storage.ts | ||
| async function resolveStorageOptions(options) {} | ||
| //#endregion | ||
| //#region src/config/resolvers/url.ts | ||
| async function resolveURLOptions(options) { | ||
| options.baseURL = withLeadingSlash(withTrailingSlash(options.baseURL)); | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/error.ts | ||
| async function resolveErrorOptions(options) { | ||
| if (!options.errorHandler) options.errorHandler = []; | ||
| else if (!Array.isArray(options.errorHandler)) options.errorHandler = [options.errorHandler]; | ||
| options.errorHandler = options.errorHandler.map((h) => resolveNitroPath(h, options)); | ||
| options.errorHandler.push(join(runtimeDir, `internal/error/${options.dev ? "dev" : "prod"}`)); | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/unenv.ts | ||
| const common = { | ||
| meta: { | ||
| name: "nitro-common", | ||
| url: import.meta.url | ||
| }, | ||
| alias: { | ||
| "buffer/": "node:buffer", | ||
| "buffer/index": "node:buffer", | ||
| "buffer/index.js": "node:buffer", | ||
| "string_decoder/": "node:string_decoder", | ||
| "process/": "node:process" | ||
| } | ||
| }; | ||
| const nodeless = { | ||
| meta: { | ||
| name: "nitro-nodeless", | ||
| url: import.meta.url | ||
| }, | ||
| inject: { | ||
| global: "unenv/polyfill/globalthis", | ||
| process: "node:process", | ||
| Buffer: ["node:buffer", "Buffer"], | ||
| clearImmediate: ["node:timers", "clearImmediate"], | ||
| setImmediate: ["node:timers", "setImmediate"], | ||
| performance: "unenv/polyfill/performance", | ||
| PerformanceObserver: ["node:perf_hooks", "PerformanceObserver"], | ||
| BroadcastChannel: ["node:worker_threads", "BroadcastChannel"] | ||
| }, | ||
| polyfill: [ | ||
| "unenv/polyfill/globalthis-global", | ||
| "unenv/polyfill/process", | ||
| "unenv/polyfill/buffer", | ||
| "unenv/polyfill/timers" | ||
| ] | ||
| }; | ||
| async function resolveUnenv(options) { | ||
| options.unenv ??= []; | ||
| if (!Array.isArray(options.unenv)) options.unenv = [options.unenv]; | ||
| options.unenv = options.unenv.filter(Boolean); | ||
| if (!options.node) options.unenv.unshift(nodeless); | ||
| options.unenv.unshift(common); | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/builder.ts | ||
| const VALID_BUILDERS = [ | ||
| "rolldown", | ||
| "rollup", | ||
| "vite" | ||
| ]; | ||
| async function resolveBuilder(options) { | ||
| options.builder ??= process.env.NITRO_BUILDER; | ||
| if (options.builder) { | ||
| if (!VALID_BUILDERS.includes(options.builder)) throw new Error(`Invalid nitro builder "${options.builder}". Valid builders are: ${VALID_BUILDERS.join(", ")}.`); | ||
| const pkg = options.builder; | ||
| if (!isPkgInstalled(pkg, options.rootDir)) { | ||
| if (!await consola$1.prompt(`Nitro builder package \`${pkg}\` is not installed. Would you like to install it?`, { | ||
| type: "confirm", | ||
| default: true, | ||
| cancel: "null" | ||
| })) throw new Error(`Nitro builder package "${options.builder}" is not installed. Please install it in your project dependencies.`); | ||
| await installPkg(pkg, options.rootDir); | ||
| } | ||
| return; | ||
| } | ||
| for (const pkg of [ | ||
| "rolldown", | ||
| "rollup", | ||
| "vite" | ||
| ]) if (isPkgInstalled(pkg, options.rootDir)) { | ||
| options.builder = pkg; | ||
| return; | ||
| } | ||
| const pkgToInstall = await consola$1.prompt(`No nitro builder specified. Which builder would you like to install?`, { | ||
| type: "select", | ||
| cancel: "null", | ||
| options: VALID_BUILDERS.map((b) => ({ | ||
| label: b, | ||
| value: b | ||
| })) | ||
| }); | ||
| if (!pkgToInstall) throw new Error(`No nitro builder specified. Please install one of the following packages: ${VALID_BUILDERS.join(", ")} and set it as the builder in your nitro config or via the NITRO_BUILDER environment variable.`); | ||
| await installPkg(pkgToInstall, options.rootDir); | ||
| options.builder = pkgToInstall; | ||
| } | ||
| const require = createRequire(process.cwd() + "/_index.js"); | ||
| function isPkgInstalled(pkg, root) { | ||
| try { | ||
| require.resolve(pkg, { paths: [root] }); | ||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
| async function installPkg(pkg, root) { | ||
| const { addDevDependency } = await import("../_libs/nypm+giget+tinyexec.mjs").then((n) => n.n); | ||
| return addDevDependency(pkg, { cwd: root }); | ||
| } | ||
| //#endregion | ||
| //#region src/config/loader.ts | ||
| const configResolvers = [ | ||
| resolveCompatibilityOptions, | ||
| resolveTsconfig, | ||
| resolvePathOptions, | ||
| resolveImportsOptions, | ||
| resolveRouteRulesOptions, | ||
| resolveDatabaseOptions, | ||
| resolveExportConditionsOptions, | ||
| resolveRuntimeConfigOptions, | ||
| resolveOpenAPIOptions, | ||
| resolveURLOptions, | ||
| resolveAssetsOptions, | ||
| resolveStorageOptions, | ||
| resolveErrorOptions, | ||
| resolveUnenv, | ||
| resolveBuilder | ||
| ]; | ||
| async function loadOptions(configOverrides = {}, opts = {}) { | ||
| const options = await _loadUserConfig(configOverrides, opts); | ||
| for (const resolver of configResolvers) await resolver(options); | ||
| return options; | ||
| } | ||
| async function _loadUserConfig(configOverrides = {}, opts = {}) { | ||
| configOverrides = klona(configOverrides); | ||
| globalThis.defineNitroConfig = globalThis.defineNitroConfig || ((c) => c); | ||
| let compatibilityDate = configOverrides.compatibilityDate || opts.compatibilityDate || process.env.NITRO_COMPATIBILITY_DATE || process.env.SERVER_COMPATIBILITY_DATE || process.env.COMPATIBILITY_DATE; | ||
| const { resolvePreset } = await import("../_presets.mjs"); | ||
| let preset = configOverrides.preset || process.env.NITRO_PRESET || process.env.SERVER_PRESET; | ||
| const _dotenv = opts.dotenv ?? (configOverrides.dev && { fileName: [".env", ".env.local"] }); | ||
| const loadedConfig = await (opts.watch ? watchConfig : loadConfig)({ | ||
| name: "nitro", | ||
| cwd: configOverrides.rootDir, | ||
| dotenv: _dotenv, | ||
| extend: { extendKey: ["extends", "preset"] }, | ||
| defaults: NitroDefaults, | ||
| jitiOptions: { alias: { | ||
| nitropack: "nitro/config", | ||
| "nitro/config": "nitro/config" | ||
| } }, | ||
| async overrides({ rawConfigs }) { | ||
| const getConf = (key) => configOverrides[key] ?? rawConfigs.main?.[key] ?? rawConfigs.rc?.[key] ?? rawConfigs.packageJson?.[key]; | ||
| if (!compatibilityDate) compatibilityDate = getConf("compatibilityDate"); | ||
| const framework = getConf("framework"); | ||
| const isCustomFramework = framework?.name && framework.name !== "nitro"; | ||
| if (!preset) preset = getConf("preset"); | ||
| if (configOverrides.dev) preset = preset && preset !== "nitro-dev" ? await resolvePreset(preset, { | ||
| static: getConf("static"), | ||
| dev: true, | ||
| compatibilityDate: compatibilityDate || "latest" | ||
| }).then((p) => p?._meta?.name || "nitro-dev").catch(() => "nitro-dev") : "nitro-dev"; | ||
| else if (!preset) preset = await resolvePreset("", { | ||
| static: getConf("static"), | ||
| dev: false, | ||
| compatibilityDate: compatibilityDate || "latest" | ||
| }).then((p) => p?._meta?.name); | ||
| return { | ||
| ...configOverrides, | ||
| preset, | ||
| typescript: { | ||
| generateRuntimeConfigTypes: !isCustomFramework, | ||
| ...getConf("typescript"), | ||
| ...configOverrides.typescript | ||
| } | ||
| }; | ||
| }, | ||
| async resolve(id) { | ||
| const preset$1 = await resolvePreset(id, { | ||
| static: configOverrides.static, | ||
| compatibilityDate: compatibilityDate || "latest", | ||
| dev: configOverrides.dev | ||
| }); | ||
| if (preset$1) return { config: klona(preset$1) }; | ||
| }, | ||
| ...opts.c12 | ||
| }); | ||
| const options = klona(loadedConfig.config); | ||
| options._config = configOverrides; | ||
| options._c12 = loadedConfig; | ||
| options.preset = (loadedConfig.layers || []).find((l) => l.config?._meta?.name)?.config?._meta?.name || preset; | ||
| options.compatibilityDate = resolveCompatibilityDates(compatibilityDate, options.compatibilityDate); | ||
| if (options.dev && options.preset !== "nitro-dev") consola$1.info(`Using \`${options.preset}\` emulation in development mode.`); | ||
| return options; | ||
| } | ||
| //#endregion | ||
| //#region src/config/update.ts | ||
| async function updateNitroConfig(nitro, config) { | ||
| nitro.options.routeRules = normalizeRouteRules(config.routeRules ? config : nitro.options); | ||
| nitro.options.runtimeConfig = normalizeRuntimeConfig(config.runtimeConfig ? config : nitro.options); | ||
| await nitro.hooks.callHook("rollup:reload"); | ||
| consola$1.success("Nitro config hot reloaded!"); | ||
| } | ||
| //#endregion | ||
| //#region src/module.ts | ||
| async function installModules(nitro) { | ||
| const _modules = [...nitro.options.modules || []]; | ||
| const modules = await Promise.all(_modules.map((mod) => _resolveNitroModule(mod, nitro.options))); | ||
| const _installedURLs = /* @__PURE__ */ new Set(); | ||
| for (const mod of modules) { | ||
| if (mod._url) { | ||
| if (_installedURLs.has(mod._url)) continue; | ||
| _installedURLs.add(mod._url); | ||
| } | ||
| await mod.setup(nitro); | ||
| } | ||
| } | ||
| async function _resolveNitroModule(mod, nitroOptions) { | ||
| let _url; | ||
| if (typeof mod === "string") mod = await import(resolveModuleURL(mod, { | ||
| from: [nitroOptions.rootDir], | ||
| extensions: [ | ||
| ".mjs", | ||
| ".cjs", | ||
| ".js", | ||
| ".mts", | ||
| ".cts", | ||
| ".ts" | ||
| ] | ||
| })).then((m) => m.default || m); | ||
| if (typeof mod === "function") mod = { setup: mod }; | ||
| if ("nitro" in mod) mod = mod.nitro; | ||
| if (!mod.setup) throw new Error("Invalid Nitro module: missing setup() function."); | ||
| return { | ||
| _url, | ||
| ...mod | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/routing.ts | ||
| const isGlobalMiddleware = (h) => !h.method && (!h.route || h.route === "/**"); | ||
| function initNitroRouting(nitro) { | ||
| const envConditions = new Set([ | ||
| nitro.options.dev ? "dev" : "prod", | ||
| nitro.options.preset, | ||
| nitro.options.preset === "nitro-prerender" ? "prerender" : void 0 | ||
| ].filter(Boolean)); | ||
| const matchesEnv = (h) => { | ||
| const envs = (Array.isArray(h.env) ? h.env : [h.env]).filter(Boolean); | ||
| return envs.length === 0 || envs.some((env) => envConditions.has(env)); | ||
| }; | ||
| const routes = new Router(nitro.options.baseURL); | ||
| const routeRules = new Router(nitro.options.baseURL); | ||
| const globalMiddleware = []; | ||
| const routedMiddleware = new Router(nitro.options.baseURL); | ||
| const sync = () => { | ||
| routeRules._update(Object.entries(nitro.options.routeRules).map(([route, data]) => ({ | ||
| route, | ||
| method: "", | ||
| data: { | ||
| ...data, | ||
| _route: route | ||
| } | ||
| }))); | ||
| const _routes = [ | ||
| ...Object.entries(nitro.options.routes).flatMap(([route, handler]) => { | ||
| if (typeof handler === "string") handler = { handler }; | ||
| return { | ||
| ...handler, | ||
| route, | ||
| middleware: false | ||
| }; | ||
| }), | ||
| ...nitro.options.handlers, | ||
| ...nitro.scannedHandlers | ||
| ].filter((h) => h && !h.middleware && matchesEnv(h)); | ||
| if (nitro.options.serverEntry && nitro.options.serverEntry.handler) _routes.push({ | ||
| route: "/**", | ||
| lazy: false, | ||
| format: nitro.options.serverEntry.format, | ||
| handler: nitro.options.serverEntry.handler | ||
| }); | ||
| if (nitro.options.renderer?.handler) _routes.push({ | ||
| route: "/**", | ||
| lazy: true, | ||
| handler: nitro.options.renderer?.handler | ||
| }); | ||
| routes._update(_routes.map((h) => ({ | ||
| ...h, | ||
| method: h.method || "", | ||
| data: handlerWithImportHash(h) | ||
| })), { merge: true }); | ||
| const _middleware = [...nitro.scannedHandlers, ...nitro.options.handlers].filter((h) => h && h.middleware && matchesEnv(h)); | ||
| if (nitro.options.serveStatic) _middleware.unshift({ | ||
| route: "/**", | ||
| middleware: true, | ||
| handler: join(runtimeDir, "internal/static") | ||
| }); | ||
| globalMiddleware.splice(0, globalMiddleware.length, ..._middleware.filter((h) => isGlobalMiddleware(h)).map((m) => handlerWithImportHash(m))); | ||
| routedMiddleware._update(_middleware.filter((h) => !isGlobalMiddleware(h)).map((h) => ({ | ||
| ...h, | ||
| method: h.method || "", | ||
| data: handlerWithImportHash(h) | ||
| }))); | ||
| }; | ||
| nitro.routing = Object.freeze({ | ||
| sync, | ||
| routes, | ||
| routeRules, | ||
| globalMiddleware, | ||
| routedMiddleware | ||
| }); | ||
| } | ||
| function handlerWithImportHash(h) { | ||
| const id = (h.lazy ? "_lazy_" : "_") + hash(h.handler).replace(/-/g, "").slice(0, 6); | ||
| return { | ||
| ...h, | ||
| _importHash: id | ||
| }; | ||
| } | ||
| var Router = class { | ||
| _routes; | ||
| _router; | ||
| _compiled; | ||
| _baseURL; | ||
| constructor(baseURL) { | ||
| this._update([]); | ||
| this._baseURL = baseURL || ""; | ||
| if (this._baseURL.endsWith("/")) this._baseURL = this._baseURL.slice(0, -1); | ||
| } | ||
| get routes() { | ||
| return this._routes; | ||
| } | ||
| _update(routes, opts) { | ||
| this._routes = routes; | ||
| this._router = createRouter(); | ||
| this._compiled = void 0; | ||
| for (const route of routes) addRoute(this._router, route.method, this._baseURL + route.route, route.data); | ||
| if (opts?.merge) mergeCatchAll(this._router); | ||
| } | ||
| hasRoutes() { | ||
| return this._routes.length > 0; | ||
| } | ||
| compileToString(opts) { | ||
| const key = opts ? hash(opts) : ""; | ||
| this._compiled ||= {}; | ||
| if (this._compiled[key]) return this._compiled[key]; | ||
| this._compiled[key] = compileRouterToString(this._router, void 0, opts); | ||
| if (this.routes.length === 1 && this.routes[0].route === "/**" && this.routes[0].method === "") { | ||
| const data = (opts?.serialize || JSON.stringify)(this.routes[0].data); | ||
| let retCode = `{data,params:{"_":p.slice(1)}}`; | ||
| if (opts?.matchAll) retCode = `[${retCode}]`; | ||
| this._compiled[key] = `/* @__PURE__ */ (() => {const data=${data};return ((_m, p)=>{return ${retCode};})})()`; | ||
| } | ||
| return this._compiled[key]; | ||
| } | ||
| match(method, path) { | ||
| return findRoute(this._router, method, path)?.data; | ||
| } | ||
| matchAll(method, path) { | ||
| return findAllRoutes(this._router, method, path).map((route) => route.data); | ||
| } | ||
| }; | ||
| function mergeCatchAll(router) { | ||
| const handlers = router.root?.wildcard?.methods?.[""]; | ||
| if (!handlers || handlers.length < 2) return; | ||
| handlers.splice(0, handlers.length, { | ||
| ...handlers[0], | ||
| data: handlers.map((h) => h.data) | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region src/global.ts | ||
| const nitroInstances = globalThis.__nitro_instances__ ||= []; | ||
| const globalKey = "__nitro_builder__"; | ||
| function registerNitroInstance(nitro) { | ||
| if (nitroInstances.includes(nitro)) return; | ||
| globalInit(); | ||
| nitroInstances.unshift(nitro); | ||
| nitro.hooks.hookOnce("close", () => { | ||
| nitroInstances.splice(nitroInstances.indexOf(nitro), 1); | ||
| if (nitroInstances.length === 0) delete globalThis[globalKey]; | ||
| }); | ||
| } | ||
| function globalInit() { | ||
| if (globalThis[globalKey]) return; | ||
| globalThis[globalKey] = { async fetch(req) { | ||
| for (let r = 0; r < 10 && nitroInstances.length === 0; r++) await new Promise((resolve$1) => setTimeout(resolve$1, 300)); | ||
| const nitro = nitroInstances[0]; | ||
| if (!nitro) throw new Error("No Nitro instance is running."); | ||
| return nitro.fetch(req); | ||
| } }; | ||
| } | ||
| //#endregion | ||
| //#region src/nitro.ts | ||
| async function createNitro(config = {}, opts = {}) { | ||
| const nitro = { | ||
| options: await loadOptions(config, opts), | ||
| hooks: new Hookable(), | ||
| vfs: /* @__PURE__ */ new Map(), | ||
| routing: {}, | ||
| logger: consola.withTag("nitro"), | ||
| scannedHandlers: [], | ||
| fetch: () => { | ||
| throw new Error("no dev server attached!"); | ||
| }, | ||
| close: () => Promise.resolve(nitro.hooks.callHook("close")), | ||
| async updateConfig(config$1) { | ||
| updateNitroConfig(nitro, config$1); | ||
| } | ||
| }; | ||
| registerNitroInstance(nitro); | ||
| initNitroRouting(nitro); | ||
| await scanAndSyncOptions(nitro); | ||
| if (nitro.options.debug) createDebugger(nitro.hooks, { tag: "nitro" }); | ||
| if (nitro.options.logLevel !== void 0) nitro.logger.level = nitro.options.logLevel; | ||
| nitro.hooks.addHooks(nitro.options.hooks); | ||
| await installModules(nitro); | ||
| if (nitro.options.imports) { | ||
| const { createUnimport } = await import("../_build/common.mjs").then((n) => n.v); | ||
| nitro.unimport = createUnimport(nitro.options.imports); | ||
| await nitro.unimport.init(); | ||
| nitro.options.virtual["#imports"] = () => nitro.unimport?.toExports() || ""; | ||
| nitro.options.virtual["#nitro"] = "export * from \"#imports\""; | ||
| } | ||
| await scanHandlers(nitro); | ||
| nitro.routing.sync(); | ||
| return nitro; | ||
| } | ||
| //#endregion | ||
| //#region src/prerender/utils.ts | ||
| const allowedExtensions = new Set(["", ".json"]); | ||
| const linkParents = /* @__PURE__ */ new Map(); | ||
| const HTML_ENTITIES = { | ||
| "<": "<", | ||
| ">": ">", | ||
| "&": "&", | ||
| "'": "'", | ||
| """: "\"" | ||
| }; | ||
| function escapeHtml(text) { | ||
| return text.replace(/&(lt|gt|amp|apos|quot);/g, (ch) => HTML_ENTITIES[ch] || ch); | ||
| } | ||
| async function extractLinks(html, from, res, crawlLinks) { | ||
| const links = []; | ||
| const _links = []; | ||
| if (crawlLinks) await z(P(html), (node) => { | ||
| if (!node.attributes?.href) return; | ||
| const link = escapeHtml(node.attributes.href); | ||
| if (!decodeURIComponent(link).startsWith("#") && allowedExtensions.has(getExtension(link))) _links.push(link); | ||
| }); | ||
| const header = res.headers.get("x-nitro-prerender") || ""; | ||
| _links.push(...header.split(",").map((i) => decodeURIComponent(i.trim()))); | ||
| for (const link of _links.filter(Boolean)) { | ||
| const _link = parseURL(link); | ||
| if (_link.protocol || _link.host) continue; | ||
| if (!_link.pathname.startsWith("/")) { | ||
| const fromURL = new URL(from, "http://localhost"); | ||
| _link.pathname = new URL(_link.pathname, fromURL).pathname; | ||
| } | ||
| links.push(_link.pathname + _link.search); | ||
| } | ||
| for (const link of links) { | ||
| const _parents = linkParents.get(link); | ||
| if (_parents) _parents.add(from); | ||
| else linkParents.set(link, new Set([from])); | ||
| } | ||
| return links; | ||
| } | ||
| const EXT_REGEX = /\.[\da-z]+$/; | ||
| function getExtension(link) { | ||
| return (parseURL(link).pathname.match(EXT_REGEX) || [])[0] || ""; | ||
| } | ||
| function formatPrerenderRoute(route) { | ||
| let str = ` ├─ ${route.route} (${route.generateTimeMS}ms)`; | ||
| if (route.error) { | ||
| const parents = linkParents.get(route.route); | ||
| const errorColor = colors[route.error.status === 404 ? "yellow" : "red"]; | ||
| const errorLead = parents?.size ? "├──" : "└──"; | ||
| str += `\n │ ${errorLead} ${errorColor(route.error.message)}`; | ||
| if (parents?.size) str += `\n${[...parents.values()].map((link) => ` │ └── Linked from ${link}`).join("\n")}`; | ||
| } | ||
| if (route.skip) str += colors.gray(" (skipped)"); | ||
| return colors.gray(str); | ||
| } | ||
| function matchesIgnorePattern(path, pattern) { | ||
| if (typeof pattern === "string") return path.startsWith(pattern); | ||
| if (typeof pattern === "function") return pattern(path) === true; | ||
| if (pattern instanceof RegExp) return pattern.test(path); | ||
| return false; | ||
| } | ||
| //#endregion | ||
| //#region src/prerender/prerender.ts | ||
| const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/; | ||
| async function prerender(nitro) { | ||
| if (nitro.options.noPublicDir) { | ||
| nitro.logger.warn("Skipping prerender since `noPublicDir` option is enabled."); | ||
| return; | ||
| } | ||
| if (nitro.options.builder === "vite") { | ||
| nitro.logger.warn("Skipping prerender since not supported with vite builder yet..."); | ||
| return; | ||
| } | ||
| const routes = new Set(nitro.options.prerender.routes); | ||
| const prerenderRulePaths = Object.entries(nitro.options.routeRules).filter(([path$1, options]) => options.prerender && !path$1.includes("*")).map((e) => e[0]); | ||
| for (const route of prerenderRulePaths) routes.add(route); | ||
| await nitro.hooks.callHook("prerender:routes", routes); | ||
| if (routes.size === 0) if (nitro.options.prerender.crawlLinks) routes.add("/"); | ||
| else return; | ||
| nitro.logger.info("Initializing prerenderer"); | ||
| nitro._prerenderedRoutes = []; | ||
| nitro._prerenderMeta = nitro._prerenderMeta || {}; | ||
| const prerendererConfig = { | ||
| ...nitro.options._config, | ||
| static: false, | ||
| rootDir: nitro.options.rootDir, | ||
| logLevel: 0, | ||
| preset: "nitro-prerender" | ||
| }; | ||
| await nitro.hooks.callHook("prerender:config", prerendererConfig); | ||
| const nitroRenderer = await createNitro(prerendererConfig); | ||
| const prerenderStartTime = Date.now(); | ||
| await nitro.hooks.callHook("prerender:init", nitroRenderer); | ||
| let path = relative(nitro.options.output.dir, nitro.options.output.publicDir); | ||
| if (!path.startsWith(".")) path = `./${path}`; | ||
| nitroRenderer.options.commands.preview = `npx serve ${path}`; | ||
| nitroRenderer.options.output.dir = nitro.options.output.dir; | ||
| await build(nitroRenderer); | ||
| const serverFilename = typeof nitroRenderer.options.rollupConfig?.output?.entryFileNames === "string" ? nitroRenderer.options.rollupConfig.output.entryFileNames : "index.mjs"; | ||
| const prerenderer = await import(pathToFileURL(resolve(nitroRenderer.options.output.serverDir, serverFilename)).href).then((m) => m.default); | ||
| const routeRules = createRouter(); | ||
| for (const [route, rules] of Object.entries(nitro.options.routeRules)) addRoute(routeRules, void 0, route, rules); | ||
| const _getRouteRules = (path$1) => defu({}, ...findAllRoutes(routeRules, void 0, path$1).map((r) => r.data).reverse()); | ||
| const generatedRoutes = /* @__PURE__ */ new Set(); | ||
| const failedRoutes = /* @__PURE__ */ new Set(); | ||
| const skippedRoutes = /* @__PURE__ */ new Set(); | ||
| const displayedLengthWarns = /* @__PURE__ */ new Set(); | ||
| const publicAssetBases = nitro.options.publicAssets.filter((a$1) => !!a$1.baseURL && a$1.baseURL !== "/" && !a$1.fallthrough).map((a$1) => withTrailingSlash(a$1.baseURL)); | ||
| const scannedPublicAssets = nitro.options.prerender.ignoreUnprefixedPublicAssets ? new Set(await scanUnprefixedPublicAssets(nitro)) : /* @__PURE__ */ new Set(); | ||
| const canPrerender = (route = "/") => { | ||
| if (generatedRoutes.has(route) || skippedRoutes.has(route)) return false; | ||
| if (nitro.options.prerender.ignore) { | ||
| for (const pattern of nitro.options.prerender.ignore) if (matchesIgnorePattern(route, pattern)) return false; | ||
| } | ||
| if (publicAssetBases.some((base) => route.startsWith(base))) return false; | ||
| if (scannedPublicAssets.has(route)) return false; | ||
| if (_getRouteRules(route).prerender === false) return false; | ||
| return true; | ||
| }; | ||
| const canWriteToDisk = (route) => { | ||
| if (route.route.includes("?")) return false; | ||
| const FS_MAX_SEGMENT = 255; | ||
| const FS_MAX_PATH_PUBLIC_HTML = 1024 - (nitro.options.output.publicDir.length + 10); | ||
| if ((route.route.length >= FS_MAX_PATH_PUBLIC_HTML || route.route.split("/").some((s) => s.length > FS_MAX_SEGMENT)) && !displayedLengthWarns.has(route)) { | ||
| displayedLengthWarns.add(route); | ||
| const _route = route.route.slice(0, 60) + "..."; | ||
| if (route.route.length >= FS_MAX_PATH_PUBLIC_HTML) nitro.logger.warn(`Prerendering long route "${_route}" (${route.route.length}) can cause filesystem issues since it exceeds ${FS_MAX_PATH_PUBLIC_HTML}-character limit when writing to \`${nitro.options.output.publicDir}\`.`); | ||
| else { | ||
| nitro.logger.warn(`Skipping prerender of the route "${_route}" since it exceeds the ${FS_MAX_SEGMENT}-character limit in one of the path segments and can cause filesystem issues.`); | ||
| return false; | ||
| } | ||
| } | ||
| return true; | ||
| }; | ||
| const generateRoute = async (route) => { | ||
| const start = Date.now(); | ||
| route = decodeURI(route); | ||
| if (!canPrerender(route)) { | ||
| skippedRoutes.add(route); | ||
| return; | ||
| } | ||
| generatedRoutes.add(route); | ||
| const _route = { route }; | ||
| const encodedRoute = encodeURI(route); | ||
| const req = toRequest(withBase(encodedRoute, nitro.options.baseURL), { headers: [["x-nitro-prerender", encodedRoute]] }); | ||
| const res = await prerenderer.fetch(req); | ||
| let dataBuff = Buffer.from(await res.arrayBuffer()); | ||
| Object.defineProperty(_route, "contents", { | ||
| get: () => { | ||
| return dataBuff ? dataBuff.toString("utf8") : void 0; | ||
| }, | ||
| set(value) { | ||
| if (dataBuff) dataBuff = Buffer.from(value); | ||
| } | ||
| }); | ||
| Object.defineProperty(_route, "data", { | ||
| get: () => { | ||
| return dataBuff ? dataBuff.buffer : void 0; | ||
| }, | ||
| set(value) { | ||
| if (dataBuff) dataBuff = Buffer.from(value); | ||
| } | ||
| }); | ||
| if (![200, ...[ | ||
| 301, | ||
| 302, | ||
| 303, | ||
| 304, | ||
| 307, | ||
| 308 | ||
| ]].includes(res.status)) { | ||
| _route.error = /* @__PURE__ */ new Error(`[${res.status}] ${res.statusText}`); | ||
| _route.error.status = res.status; | ||
| _route.error.statusText = res.statusText; | ||
| } | ||
| _route.generateTimeMS = Date.now() - start; | ||
| const contentType = res.headers.get("content-type") || ""; | ||
| const isImplicitHTML = !route.endsWith(".html") && contentType.includes("html") && !JsonSigRx.test(dataBuff.subarray(0, 32).toString("utf8")); | ||
| const routeWithIndex = route.endsWith("/") ? route + "index" : route; | ||
| const htmlPath = route.endsWith("/") || nitro.options.prerender.autoSubfolderIndex ? joinURL(route, "index.html") : route + ".html"; | ||
| _route.fileName = withoutBase(isImplicitHTML ? htmlPath : routeWithIndex, nitro.options.baseURL); | ||
| const inferredContentType = src_default.getType(_route.fileName) || "text/plain"; | ||
| _route.contentType = contentType || inferredContentType; | ||
| await nitro.hooks.callHook("prerender:generate", _route, nitro); | ||
| if (_route.contentType !== inferredContentType) { | ||
| nitro._prerenderMeta[_route.fileName] ||= {}; | ||
| nitro._prerenderMeta[_route.fileName].contentType = _route.contentType; | ||
| } | ||
| if (_route.error) failedRoutes.add(_route); | ||
| if (_route.skip || _route.error) { | ||
| await nitro.hooks.callHook("prerender:route", _route); | ||
| nitro.logger.log(formatPrerenderRoute(_route)); | ||
| dataBuff = void 0; | ||
| return _route; | ||
| } | ||
| if (canWriteToDisk(_route)) { | ||
| await writeFile$1(join(nitro.options.output.publicDir, _route.fileName), dataBuff); | ||
| nitro._prerenderedRoutes.push(_route); | ||
| } else _route.skip = true; | ||
| if (!_route.error && (isImplicitHTML || route.endsWith(".html"))) { | ||
| const extractedLinks = await extractLinks(dataBuff.toString("utf8"), route, res, nitro.options.prerender.crawlLinks ?? false); | ||
| for (const _link of extractedLinks) if (canPrerender(_link)) routes.add(_link); | ||
| } | ||
| await nitro.hooks.callHook("prerender:route", _route); | ||
| nitro.logger.log(formatPrerenderRoute(_route)); | ||
| dataBuff = void 0; | ||
| return _route; | ||
| }; | ||
| nitro.logger.info(nitro.options.prerender.crawlLinks ? `Prerendering ${routes.size} initial routes with crawler` : `Prerendering ${routes.size} routes`); | ||
| await runParallel(routes, generateRoute, { | ||
| concurrency: nitro.options.prerender.concurrency || 1, | ||
| interval: nitro.options.prerender.interval | ||
| }); | ||
| await prerenderer.close(); | ||
| await nitro.hooks.callHook("prerender:done", { | ||
| prerenderedRoutes: nitro._prerenderedRoutes, | ||
| failedRoutes: [...failedRoutes] | ||
| }); | ||
| if (nitro.options.prerender.failOnError && failedRoutes.size > 0) { | ||
| nitro.logger.log("\nErrors prerendering:"); | ||
| for (const route of failedRoutes) nitro.logger.log(formatPrerenderRoute(route)); | ||
| nitro.logger.log(""); | ||
| throw new Error("Exiting due to prerender errors."); | ||
| } | ||
| const prerenderTimeInMs = Date.now() - prerenderStartTime; | ||
| nitro.logger.info(`Prerendered ${nitro._prerenderedRoutes.length} routes in ${prerenderTimeInMs / 1e3} seconds`); | ||
| if (nitro.options.compressPublicAssets) await compressPublicAssets(nitro); | ||
| } | ||
| //#endregion | ||
| //#region src/task.ts | ||
| /** @experimental */ | ||
| async function runTask(taskEvent, opts) { | ||
| return await (await _getTasksContext(opts)).devFetch(`/_nitro/tasks/${taskEvent.name}`, { | ||
| method: "POST", | ||
| body: taskEvent | ||
| }); | ||
| } | ||
| /** @experimental */ | ||
| async function listTasks(opts) { | ||
| return (await (await _getTasksContext(opts)).devFetch("/_nitro/tasks")).tasks; | ||
| } | ||
| const _devHint = `(is dev server running?)`; | ||
| async function _getTasksContext(opts) { | ||
| const buildInfoPath = resolve(resolve(resolve(process.cwd(), opts?.cwd || "."), opts?.buildDir || "node_modules/.nitro"), "nitro.dev.json"); | ||
| if (!existsSync(buildInfoPath)) throw new Error(`Missing info file: \`${buildInfoPath}\` ${_devHint}`); | ||
| const buildInfo = JSON.parse(await readFile(buildInfoPath, "utf8")); | ||
| if (!buildInfo.dev?.pid || !buildInfo.dev?.workerAddress) throw new Error(`Missing dev server info in: \`${buildInfoPath}\` ${_devHint}`); | ||
| if (!_pidIsRunning(buildInfo.dev.pid)) throw new Error(`Dev server is not running (pid: ${buildInfo.dev.pid})`); | ||
| const baseURL = `http://${buildInfo.dev.workerAddress.host || "localhost"}:${buildInfo.dev.workerAddress.port || "3000"}`; | ||
| const socketPath = buildInfo.dev.workerAddress.socketPath; | ||
| const devFetch = (path, options) => { | ||
| return new Promise((resolve$1, reject) => { | ||
| let url = withBase(path, baseURL); | ||
| if (options?.query) url = withQuery(url, options.query); | ||
| const request = http.request(url, { | ||
| socketPath, | ||
| method: options?.method, | ||
| headers: { | ||
| Accept: "application/json", | ||
| "Content-Type": "application/json" | ||
| } | ||
| }, (response) => { | ||
| if (!response.statusCode || response.statusCode >= 400 && response.statusCode < 600) { | ||
| reject(new Error(response.statusMessage)); | ||
| return; | ||
| } | ||
| let data = ""; | ||
| response.on("data", (chunk) => data += chunk).on("end", () => resolve$1(JSON.parse(data))).on("error", (e) => reject(e)); | ||
| }); | ||
| request.on("error", (e) => reject(e)); | ||
| if (options?.body) request.write(JSON.stringify(options.body)); | ||
| request.end(); | ||
| }); | ||
| }; | ||
| return { | ||
| buildInfo, | ||
| devFetch | ||
| }; | ||
| } | ||
| function _pidIsRunning(pid) { | ||
| try { | ||
| process.kill(pid, 0); | ||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
| //#endregion | ||
| export { loadOptions as a, createNitro as i, runTask as n, prerender as r, listTasks as t }; |
| import { N as glob, at as join, st as relative } from "../_build/common.mjs"; | ||
| import { withBase, withLeadingSlash, withoutTrailingSlash } from "ufo"; | ||
| //#region src/scan.ts | ||
| const GLOB_SCAN_PATTERN = "**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}"; | ||
| const suffixRegex = /(\.(?<method>connect|delete|get|head|options|patch|post|put|trace))?(\.(?<env>dev|prod|prerender))?$/; | ||
| async function scanAndSyncOptions(nitro) { | ||
| const scannedPlugins = await scanPlugins(nitro); | ||
| for (const plugin of scannedPlugins) if (!nitro.options.plugins.includes(plugin)) nitro.options.plugins.push(plugin); | ||
| if (nitro.options.experimental.tasks) { | ||
| const scannedTasks = await scanTasks(nitro); | ||
| for (const scannedTask of scannedTasks) if (scannedTask.name in nitro.options.tasks) { | ||
| if (!nitro.options.tasks[scannedTask.name].handler) nitro.options.tasks[scannedTask.name].handler = scannedTask.handler; | ||
| } else nitro.options.tasks[scannedTask.name] = { | ||
| handler: scannedTask.handler, | ||
| description: "" | ||
| }; | ||
| } | ||
| const scannedModules = await scanModules(nitro); | ||
| nitro.options.modules = nitro.options.modules || []; | ||
| for (const modPath of scannedModules) if (!nitro.options.modules.includes(modPath)) nitro.options.modules.push(modPath); | ||
| } | ||
| async function scanHandlers(nitro) { | ||
| const middleware = await scanMiddleware(nitro); | ||
| const handlers = await Promise.all([scanServerRoutes(nitro, nitro.options.apiDir || "api", nitro.options.apiBaseURL || "/api"), scanServerRoutes(nitro, nitro.options.routesDir || "routes")]).then((r) => r.flat()); | ||
| nitro.scannedHandlers = [...middleware, ...handlers.filter((h, index, array) => { | ||
| return array.findIndex((h2) => h.route === h2.route && h.method === h2.method && h.env === h2.env) === index; | ||
| })]; | ||
| return handlers; | ||
| } | ||
| async function scanMiddleware(nitro) { | ||
| return (await scanFiles(nitro, "middleware")).map((file) => { | ||
| return { | ||
| route: "/**", | ||
| middleware: true, | ||
| handler: file.fullPath | ||
| }; | ||
| }); | ||
| } | ||
| async function scanServerRoutes(nitro, dir, prefix = "/") { | ||
| return (await scanFiles(nitro, dir)).map((file) => { | ||
| let route = file.path.replace(/\.[A-Za-z]+$/, "").replace(/\(([^(/\\]+)\)[/\\]/g, "").replace(/\[\.{3}]/g, "**").replace(/\[\.{3}(\w+)]/g, "**:$1").replace(/\[([^/\]]+)]/g, ":$1"); | ||
| route = withLeadingSlash(withoutTrailingSlash(withBase(route, prefix))); | ||
| const suffixMatch = route.match(suffixRegex); | ||
| let method; | ||
| let env; | ||
| if (suffixMatch?.index && suffixMatch?.index >= 0) { | ||
| route = route.slice(0, suffixMatch.index); | ||
| method = suffixMatch.groups?.method; | ||
| env = suffixMatch.groups?.env; | ||
| } | ||
| route = route.replace(/\/index$/, "") || "/"; | ||
| return { | ||
| handler: file.fullPath, | ||
| lazy: true, | ||
| middleware: false, | ||
| route, | ||
| method, | ||
| env | ||
| }; | ||
| }); | ||
| } | ||
| async function scanPlugins(nitro) { | ||
| return (await scanFiles(nitro, "plugins")).map((f) => f.fullPath); | ||
| } | ||
| async function scanTasks(nitro) { | ||
| return (await scanFiles(nitro, "tasks")).map((f) => { | ||
| return { | ||
| name: f.path.replace(/\/index$/, "").replace(/\.[A-Za-z]+$/, "").replace(/\//g, ":"), | ||
| handler: f.fullPath | ||
| }; | ||
| }); | ||
| } | ||
| async function scanModules(nitro) { | ||
| return (await scanFiles(nitro, "modules")).map((f) => f.fullPath); | ||
| } | ||
| async function scanFiles(nitro, name) { | ||
| return await Promise.all(nitro.options.scanDirs.map((dir) => scanDir(nitro, dir, name))).then((r) => r.flat()); | ||
| } | ||
| async function scanDir(nitro, dir, name) { | ||
| return (await glob(join(name, GLOB_SCAN_PATTERN), { | ||
| cwd: dir, | ||
| dot: true, | ||
| ignore: nitro.options.ignore, | ||
| absolute: true | ||
| }).catch((error) => { | ||
| if (error?.code === "ENOTDIR") { | ||
| nitro.logger.warn(`Ignoring \`${join(dir, name)}\`. It must be a directory.`); | ||
| return []; | ||
| } | ||
| throw error; | ||
| })).map((fullPath) => { | ||
| return { | ||
| fullPath, | ||
| path: relative(join(dir, name), fullPath) | ||
| }; | ||
| }).sort((a, b) => a.path.localeCompare(b.path)); | ||
| } | ||
| //#endregion | ||
| export { scanHandlers as n, scanAndSyncOptions as t }; |
| import { i as __toESM, r as __require, t as __commonJSMin } from "../_common.mjs"; | ||
| import { N as glob, V as a, ct as resolve, nt as dirname, p as runParallel, st as relative } from "../_build/common.mjs"; | ||
| import fs, { promises } from "node:fs"; | ||
| import { promisify } from "node:util"; | ||
| import { colors } from "consola/utils"; | ||
| import zlib from "node:zlib"; | ||
| import "node:stream"; | ||
| //#region node_modules/.pnpm/duplexer@0.1.2/node_modules/duplexer/index.js | ||
| var require_duplexer = /* @__PURE__ */ __commonJSMin(((exports, module) => { | ||
| var Stream = __require("stream"); | ||
| var writeMethods = [ | ||
| "write", | ||
| "end", | ||
| "destroy" | ||
| ]; | ||
| var readMethods = ["resume", "pause"]; | ||
| var readEvents = ["data", "close"]; | ||
| var slice = Array.prototype.slice; | ||
| module.exports = duplex; | ||
| function forEach(arr, fn) { | ||
| if (arr.forEach) return arr.forEach(fn); | ||
| for (var i = 0; i < arr.length; i++) fn(arr[i], i); | ||
| } | ||
| function duplex(writer, reader) { | ||
| var stream = new Stream(); | ||
| var ended = false; | ||
| forEach(writeMethods, proxyWriter); | ||
| forEach(readMethods, proxyReader); | ||
| forEach(readEvents, proxyStream); | ||
| reader.on("end", handleEnd); | ||
| writer.on("drain", function() { | ||
| stream.emit("drain"); | ||
| }); | ||
| writer.on("error", reemit); | ||
| reader.on("error", reemit); | ||
| stream.writable = writer.writable; | ||
| stream.readable = reader.readable; | ||
| return stream; | ||
| function proxyWriter(methodName) { | ||
| stream[methodName] = method; | ||
| function method() { | ||
| return writer[methodName].apply(writer, arguments); | ||
| } | ||
| } | ||
| function proxyReader(methodName) { | ||
| stream[methodName] = method; | ||
| function method() { | ||
| stream.emit(methodName); | ||
| var func = reader[methodName]; | ||
| if (func) return func.apply(reader, arguments); | ||
| reader.emit(methodName); | ||
| } | ||
| } | ||
| function proxyStream(methodName) { | ||
| reader.on(methodName, reemit$1); | ||
| function reemit$1() { | ||
| var args = slice.call(arguments); | ||
| args.unshift(methodName); | ||
| stream.emit.apply(stream, args); | ||
| } | ||
| } | ||
| function handleEnd() { | ||
| if (ended) return; | ||
| ended = true; | ||
| var args = slice.call(arguments); | ||
| args.unshift("end"); | ||
| stream.emit.apply(stream, args); | ||
| } | ||
| function reemit(err) { | ||
| stream.emit("error", err); | ||
| } | ||
| } | ||
| })); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/gzip-size@7.0.0/node_modules/gzip-size/index.js | ||
| var import_duplexer = /* @__PURE__ */ __toESM(require_duplexer(), 1); | ||
| const getOptions = (options) => ({ | ||
| level: 9, | ||
| ...options | ||
| }); | ||
| const gzip = promisify(zlib.gzip); | ||
| async function gzipSize(input, options) { | ||
| if (!input) return 0; | ||
| return (await gzip(input, getOptions(options))).length; | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/pretty-bytes@7.1.0/node_modules/pretty-bytes/index.js | ||
| const BYTE_UNITS = [ | ||
| "B", | ||
| "kB", | ||
| "MB", | ||
| "GB", | ||
| "TB", | ||
| "PB", | ||
| "EB", | ||
| "ZB", | ||
| "YB" | ||
| ]; | ||
| const BIBYTE_UNITS = [ | ||
| "B", | ||
| "KiB", | ||
| "MiB", | ||
| "GiB", | ||
| "TiB", | ||
| "PiB", | ||
| "EiB", | ||
| "ZiB", | ||
| "YiB" | ||
| ]; | ||
| const BIT_UNITS = [ | ||
| "b", | ||
| "kbit", | ||
| "Mbit", | ||
| "Gbit", | ||
| "Tbit", | ||
| "Pbit", | ||
| "Ebit", | ||
| "Zbit", | ||
| "Ybit" | ||
| ]; | ||
| const BIBIT_UNITS = [ | ||
| "b", | ||
| "kibit", | ||
| "Mibit", | ||
| "Gibit", | ||
| "Tibit", | ||
| "Pibit", | ||
| "Eibit", | ||
| "Zibit", | ||
| "Yibit" | ||
| ]; | ||
| const toLocaleString = (number, locale, options) => { | ||
| let result = number; | ||
| if (typeof locale === "string" || Array.isArray(locale)) result = number.toLocaleString(locale, options); | ||
| else if (locale === true || options !== void 0) result = number.toLocaleString(void 0, options); | ||
| return result; | ||
| }; | ||
| const log10 = (numberOrBigInt) => { | ||
| if (typeof numberOrBigInt === "number") return Math.log10(numberOrBigInt); | ||
| const string = numberOrBigInt.toString(10); | ||
| return string.length + Math.log10(`0.${string.slice(0, 15)}`); | ||
| }; | ||
| const log = (numberOrBigInt) => { | ||
| if (typeof numberOrBigInt === "number") return Math.log(numberOrBigInt); | ||
| return log10(numberOrBigInt) * Math.log(10); | ||
| }; | ||
| const divide = (numberOrBigInt, divisor) => { | ||
| if (typeof numberOrBigInt === "number") return numberOrBigInt / divisor; | ||
| const integerPart = numberOrBigInt / BigInt(divisor); | ||
| const remainder = numberOrBigInt % BigInt(divisor); | ||
| return Number(integerPart) + Number(remainder) / divisor; | ||
| }; | ||
| const applyFixedWidth = (result, fixedWidth) => { | ||
| if (fixedWidth === void 0) return result; | ||
| if (typeof fixedWidth !== "number" || !Number.isSafeInteger(fixedWidth) || fixedWidth < 0) throw new TypeError(`Expected fixedWidth to be a non-negative integer, got ${typeof fixedWidth}: ${fixedWidth}`); | ||
| if (fixedWidth === 0) return result; | ||
| return result.length < fixedWidth ? result.padStart(fixedWidth, " ") : result; | ||
| }; | ||
| const buildLocaleOptions = (options) => { | ||
| const { minimumFractionDigits, maximumFractionDigits } = options; | ||
| if (minimumFractionDigits === void 0 && maximumFractionDigits === void 0) return; | ||
| return { | ||
| ...minimumFractionDigits !== void 0 && { minimumFractionDigits }, | ||
| ...maximumFractionDigits !== void 0 && { maximumFractionDigits }, | ||
| roundingMode: "trunc" | ||
| }; | ||
| }; | ||
| function prettyBytes(number, options) { | ||
| if (typeof number !== "bigint" && !Number.isFinite(number)) throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`); | ||
| options = { | ||
| bits: false, | ||
| binary: false, | ||
| space: true, | ||
| nonBreakingSpace: false, | ||
| ...options | ||
| }; | ||
| const UNITS = options.bits ? options.binary ? BIBIT_UNITS : BIT_UNITS : options.binary ? BIBYTE_UNITS : BYTE_UNITS; | ||
| const separator = options.space ? options.nonBreakingSpace ? "\xA0" : " " : ""; | ||
| const isZero = typeof number === "number" ? number === 0 : number === 0n; | ||
| if (options.signed && isZero) return applyFixedWidth(` 0${separator}${UNITS[0]}`, options.fixedWidth); | ||
| const isNegative = number < 0; | ||
| const prefix = isNegative ? "-" : options.signed ? "+" : ""; | ||
| if (isNegative) number = -number; | ||
| const localeOptions = buildLocaleOptions(options); | ||
| let result; | ||
| if (number < 1) result = prefix + toLocaleString(number, options.locale, localeOptions) + separator + UNITS[0]; | ||
| else { | ||
| const exponent = Math.min(Math.floor(options.binary ? log(number) / Math.log(1024) : log10(number) / 3), UNITS.length - 1); | ||
| number = divide(number, (options.binary ? 1024 : 1e3) ** exponent); | ||
| if (!localeOptions) { | ||
| const minPrecision = Math.max(3, Math.floor(number).toString().length); | ||
| number = number.toPrecision(minPrecision); | ||
| } | ||
| const numberString = toLocaleString(Number(number), options.locale, localeOptions); | ||
| const unit = UNITS[exponent]; | ||
| result = prefix + numberString + separator + unit; | ||
| } | ||
| return applyFixedWidth(result, options.fixedWidth); | ||
| } | ||
| //#endregion | ||
| //#region src/utils/fs-tree.ts | ||
| async function generateFSTree(dir, options = {}) { | ||
| if (a) return; | ||
| const files = await glob("**/*.*", { | ||
| cwd: dir, | ||
| ignore: ["*.map"] | ||
| }); | ||
| const items = []; | ||
| await runParallel(new Set(files), async (file) => { | ||
| const path = resolve(dir, file); | ||
| const src = await promises.readFile(path); | ||
| const size = src.byteLength; | ||
| const gzip$1 = options.compressedSizes ? await gzipSize(src) : 0; | ||
| items.push({ | ||
| file, | ||
| path, | ||
| size, | ||
| gzip: gzip$1 | ||
| }); | ||
| }, { concurrency: 10 }); | ||
| items.sort((a$1, b) => a$1.path.localeCompare(b.path)); | ||
| let totalSize = 0; | ||
| let totalGzip = 0; | ||
| let totalNodeModulesSize = 0; | ||
| let totalNodeModulesGzip = 0; | ||
| let treeText = ""; | ||
| for (const [index, item] of items.entries()) { | ||
| let dir$1 = dirname(item.file); | ||
| if (dir$1 === ".") dir$1 = ""; | ||
| const rpath = relative(process.cwd(), item.path); | ||
| const treeChar = index === items.length - 1 ? "└─" : "├─"; | ||
| if (item.file.includes("node_modules")) { | ||
| totalNodeModulesSize += item.size; | ||
| totalNodeModulesGzip += item.gzip; | ||
| continue; | ||
| } | ||
| treeText += colors.gray(` ${treeChar} ${rpath} (${prettyBytes(item.size)})`); | ||
| if (options.compressedSizes) treeText += colors.gray(` (${prettyBytes(item.gzip)} gzip)`); | ||
| treeText += "\n"; | ||
| totalSize += item.size; | ||
| totalGzip += item.gzip; | ||
| } | ||
| treeText += `${colors.cyan("Σ Total size:")} ${prettyBytes(totalSize + totalNodeModulesSize)}`; | ||
| if (options.compressedSizes) treeText += ` (${prettyBytes(totalGzip + totalNodeModulesGzip)} gzip)`; | ||
| treeText += "\n"; | ||
| return treeText; | ||
| } | ||
| //#endregion | ||
| export { generateFSTree as t }; |
| import { createRequire } from "node:module"; | ||
| //#region rolldown:runtime | ||
| var __create = Object.create; | ||
| var __defProp = Object.defineProperty; | ||
| var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
| var __getOwnPropNames = Object.getOwnPropertyNames; | ||
| var __getProtoOf = Object.getPrototypeOf; | ||
| var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
| var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); | ||
| var __exportAll = (all, symbols) => { | ||
| let target = {}; | ||
| for (var name in all) { | ||
| __defProp(target, name, { | ||
| get: all[name], | ||
| enumerable: true | ||
| }); | ||
| } | ||
| if (symbols) { | ||
| __defProp(target, Symbol.toStringTag, { value: "Module" }); | ||
| } | ||
| return target; | ||
| }; | ||
| var __copyProps = (to, from, except, desc) => { | ||
| if (from && typeof from === "object" || typeof from === "function") { | ||
| for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { | ||
| key = keys[i]; | ||
| if (!__hasOwnProp.call(to, key) && key !== except) { | ||
| __defProp(to, key, { | ||
| get: ((k) => from[k]).bind(null, key), | ||
| enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable | ||
| }); | ||
| } | ||
| } | ||
| } | ||
| return to; | ||
| }; | ||
| var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { | ||
| value: mod, | ||
| enumerable: true | ||
| }) : target, mod)); | ||
| var __require = /* @__PURE__ */ createRequire(import.meta.url); | ||
| //#endregion | ||
| export { __toESM as i, __exportAll as n, __require as r, __commonJSMin as t }; |
| import { Stats } from "node:fs"; | ||
| import { Jiti, JitiOptions } from "jiti"; | ||
| import { EventEmitter } from "node:events"; | ||
| import { Readable } from "node:stream"; | ||
| import { diff } from "ohash/utils"; | ||
| //#region node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/index.d.ts | ||
| type AWF = { | ||
| stabilityThreshold: number; | ||
| pollInterval: number; | ||
| }; | ||
| type BasicOpts = { | ||
| persistent: boolean; | ||
| ignoreInitial: boolean; | ||
| followSymlinks: boolean; | ||
| cwd?: string; | ||
| usePolling: boolean; | ||
| interval: number; | ||
| binaryInterval: number; | ||
| alwaysStat?: boolean; | ||
| depth?: number; | ||
| ignorePermissionErrors: boolean; | ||
| atomic: boolean | number; | ||
| }; | ||
| type ChokidarOptions = Partial<BasicOpts & { | ||
| ignored: Matcher | Matcher[]; | ||
| awaitWriteFinish: boolean | Partial<AWF>; | ||
| }>; | ||
| type MatchFunction = (val: string, stats?: Stats) => boolean; | ||
| interface MatcherObject { | ||
| path: string; | ||
| recursive?: boolean; | ||
| } | ||
| type Matcher = string | RegExp | MatchFunction | MatcherObject; | ||
| //#endregion | ||
| //#region node_modules/.pnpm/giget@2.0.0/node_modules/giget/dist/index.d.mts | ||
| interface TemplateInfo { | ||
| name: string; | ||
| tar: string; | ||
| version?: string; | ||
| subdir?: string; | ||
| url?: string; | ||
| defaultDir?: string; | ||
| headers?: Record<string, string | undefined>; | ||
| source?: never; | ||
| dir?: never; | ||
| [key: string]: any; | ||
| } | ||
| type TemplateProvider = (input: string, options: { | ||
| auth?: string; | ||
| }) => TemplateInfo | Promise<TemplateInfo> | null; | ||
| interface DownloadTemplateOptions { | ||
| provider?: string; | ||
| force?: boolean; | ||
| forceClean?: boolean; | ||
| offline?: boolean; | ||
| preferOffline?: boolean; | ||
| providers?: Record<string, TemplateProvider>; | ||
| dir?: string; | ||
| registry?: false | string; | ||
| cwd?: string; | ||
| auth?: string; | ||
| install?: boolean; | ||
| silent?: boolean; | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/c12@3.3.3_magicast@0.5.1/node_modules/c12/dist/index.d.mts | ||
| //#region src/dotenv.d.ts | ||
| interface DotenvOptions { | ||
| /** | ||
| * The project root directory (either absolute or relative to the current working directory). | ||
| * | ||
| * Defaults to `options.cwd` in `loadConfig` context, or `process.cwd()` when used as standalone. | ||
| */ | ||
| cwd?: string; | ||
| /** | ||
| * What file or files to look in for environment variables (either absolute or relative | ||
| * to the current working directory). For example, `.env`. | ||
| * With the array type, the order enforce the env loading priority (last one overrides). | ||
| */ | ||
| fileName?: string | string[]; | ||
| /** | ||
| * Whether to interpolate variables within .env. | ||
| * | ||
| * @example | ||
| * ```env | ||
| * BASE_DIR="/test" | ||
| * # resolves to "/test/further" | ||
| * ANOTHER_DIR="${BASE_DIR}/further" | ||
| * ``` | ||
| */ | ||
| interpolate?: boolean; | ||
| /** | ||
| * An object describing environment variables (key, value pairs). | ||
| */ | ||
| env?: NodeJS.ProcessEnv; | ||
| } | ||
| declare global { | ||
| var __c12_dotenv_vars__: Map<Record<string, any>, Set<string>>; | ||
| } //#endregion | ||
| //#region src/types.d.ts | ||
| interface ConfigLayerMeta { | ||
| name?: string; | ||
| [key: string]: any; | ||
| } | ||
| type UserInputConfig = Record<string, any>; | ||
| interface C12InputConfig<T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta> { | ||
| $test?: T; | ||
| $development?: T; | ||
| $production?: T; | ||
| $env?: Record<string, T>; | ||
| $meta?: MT; | ||
| } | ||
| interface SourceOptions<T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta> { | ||
| /** Custom meta for layer */ | ||
| meta?: MT; | ||
| /** Layer config overrides */ | ||
| overrides?: T; | ||
| [key: string]: any; | ||
| /** | ||
| * Options for cloning remote sources | ||
| * | ||
| * @see https://giget.unjs.io | ||
| */ | ||
| giget?: DownloadTemplateOptions; | ||
| /** | ||
| * Install dependencies after cloning | ||
| * | ||
| * @see https://nypm.unjs.io | ||
| */ | ||
| install?: boolean; | ||
| /** | ||
| * Token for cloning private sources | ||
| * | ||
| * @see https://giget.unjs.io#providing-token-for-private-repositories | ||
| */ | ||
| auth?: string; | ||
| } | ||
| interface ConfigLayer<T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta> { | ||
| config: T | null; | ||
| source?: string; | ||
| sourceOptions?: SourceOptions<T, MT>; | ||
| meta?: MT; | ||
| cwd?: string; | ||
| configFile?: string; | ||
| } | ||
| interface ResolvedConfig<T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta> extends ConfigLayer<T, MT> { | ||
| config: T; | ||
| layers?: ConfigLayer<T, MT>[]; | ||
| cwd?: string; | ||
| _configFile?: string; | ||
| } | ||
| type ConfigSource = "overrides" | "main" | "rc" | "packageJson" | "defaultConfig"; | ||
| interface ConfigFunctionContext { | ||
| [key: string]: any; | ||
| } | ||
| interface ResolvableConfigContext<T extends UserInputConfig = UserInputConfig> { | ||
| configs: Record<ConfigSource, T | null | undefined>; | ||
| rawConfigs: Record<ConfigSource, ResolvableConfig<T> | null | undefined>; | ||
| } | ||
| type MaybePromise<T> = T | Promise<T>; | ||
| type ResolvableConfig<T extends UserInputConfig = UserInputConfig> = MaybePromise<T | null | undefined> | ((ctx: ResolvableConfigContext<T>) => MaybePromise<T | null | undefined>); | ||
| interface LoadConfigOptions<T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta> { | ||
| name?: string; | ||
| cwd?: string; | ||
| configFile?: string; | ||
| rcFile?: false | string; | ||
| globalRc?: boolean; | ||
| dotenv?: boolean | DotenvOptions; | ||
| envName?: string | false; | ||
| packageJson?: boolean | string | string[]; | ||
| defaults?: T; | ||
| defaultConfig?: ResolvableConfig<T>; | ||
| overrides?: ResolvableConfig<T>; | ||
| omit$Keys?: boolean; | ||
| /** Context passed to config functions */ | ||
| context?: ConfigFunctionContext; | ||
| resolve?: (id: string, options: LoadConfigOptions<T, MT>) => null | undefined | ResolvedConfig<T, MT> | Promise<ResolvedConfig<T, MT> | undefined | null>; | ||
| jiti?: Jiti; | ||
| jitiOptions?: JitiOptions; | ||
| giget?: false | DownloadTemplateOptions; | ||
| merger?: (...sources: Array<T | null | undefined>) => T; | ||
| extend?: false | { | ||
| extendKey?: string | string[]; | ||
| }; | ||
| configFileRequired?: boolean; | ||
| } | ||
| //#endregion | ||
| //#region src/watch.d.ts | ||
| type DiffEntries = ReturnType<typeof diff>; | ||
| type ConfigWatcher<T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta> = ResolvedConfig<T, MT> & { | ||
| watchingFiles: string[]; | ||
| unwatch: () => Promise<void>; | ||
| }; | ||
| interface WatchConfigOptions<T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta> extends LoadConfigOptions<T, MT> { | ||
| chokidarOptions?: ChokidarOptions; | ||
| debounce?: false | number; | ||
| onWatch?: (event: { | ||
| type: "created" | "updated" | "removed"; | ||
| path: string; | ||
| }) => void | Promise<void>; | ||
| acceptHMR?: (context: { | ||
| getDiff: () => DiffEntries; | ||
| newConfig: ResolvedConfig<T, MT>; | ||
| oldConfig: ResolvedConfig<T, MT>; | ||
| }) => void | boolean | Promise<void | boolean>; | ||
| onUpdate?: (context: { | ||
| getDiff: () => ReturnType<typeof diff>; | ||
| newConfig: ResolvedConfig<T, MT>; | ||
| oldConfig: ResolvedConfig<T, MT>; | ||
| }) => void | Promise<void>; | ||
| } | ||
| //#endregion | ||
| export { WatchConfigOptions as a, ResolvedConfig as i, ConfigWatcher as n, ChokidarOptions as o, DotenvOptions as r, C12InputConfig as t }; |
Sorry, the diff of this file is too big to display
| //#region node_modules/.pnpm/compatx@0.2.0/node_modules/compatx/dist/index.d.mts | ||
| /** | ||
| * Known platform names | ||
| */ | ||
| declare const platforms: readonly ["aws", "azure", "cloudflare", "deno", "firebase", "netlify", "vercel"]; | ||
| /** | ||
| * Known platform name | ||
| */ | ||
| type PlatformName = (typeof platforms)[number] | (string & {}); | ||
| /** | ||
| * Normalize the compatibility dates from input config and defaults. | ||
| */ | ||
| type Year = `${number}${number}${number}${number}`; | ||
| type Month = `${"0" | "1"}${number}`; | ||
| type Day = `${"0" | "1" | "2" | "3"}${number}`; | ||
| /** | ||
| * Typed date string in `YYYY-MM-DD` format | ||
| * | ||
| * Empty string is used to represent an "unspecified" date. | ||
| * | ||
| * "latest" is used to represent the latest date available (date of today). | ||
| */ | ||
| type DateString = "" | "latest" | `${Year}-${Month}-${Day}`; | ||
| /** | ||
| * Last known compatibility dates for platforms | ||
| * | ||
| * @example | ||
| * { | ||
| * "default": "2024-01-01", | ||
| * "cloudflare": "2024-03-01", | ||
| * } | ||
| */ | ||
| type CompatibilityDates = { | ||
| /** | ||
| * Default compatibility date for all unspecified platforms (required) | ||
| */ | ||
| default: DateString; | ||
| } & Partial<Record<PlatformName, DateString>>; | ||
| /** | ||
| * Last known compatibility date for the used platform | ||
| */ | ||
| type CompatibilityDateSpec = DateString | Partial<CompatibilityDates>; | ||
| /** | ||
| * Get compatibility updates applicable for the user given platform and date range. | ||
| */ | ||
| //#endregion | ||
| export { CompatibilityDates as n, DateString as r, CompatibilityDateSpec as t }; |
| //#region node_modules/.pnpm/esbuild@0.27.2/node_modules/esbuild/lib/main.d.ts | ||
| // Note: These declarations exist to avoid type errors when you omit "dom" from | ||
| // "lib" in your "tsconfig.json" file. TypeScript confusingly declares the | ||
| // global "WebAssembly" type in "lib.dom.d.ts" even though it has nothing to do | ||
| // with the browser DOM and is present in many non-browser JavaScript runtimes | ||
| // (e.g. node and deno). Declaring it here allows esbuild's API to be used in | ||
| // these scenarios. | ||
| // | ||
| // There's an open issue about getting this problem corrected (although these | ||
| // declarations will need to remain even if this is fixed for backward | ||
| // compatibility with older TypeScript versions): | ||
| // | ||
| // https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/826 | ||
| // | ||
| declare global { | ||
| namespace WebAssembly { | ||
| interface Module {} | ||
| } | ||
| interface URL {} | ||
| } |
Sorry, the diff of this file is too big to display
| import http, { IncomingMessage, OutgoingMessage } from "node:http"; | ||
| import { EventEmitter } from "node:events"; | ||
| import * as stream from "node:stream"; | ||
| //#region node_modules/.pnpm/httpxy@0.1.7/node_modules/httpxy/dist/index.d.ts | ||
| interface ProxyTargetDetailed { | ||
| host: string; | ||
| port: number; | ||
| protocol?: string; | ||
| hostname?: string; | ||
| socketPath?: string; | ||
| key?: string; | ||
| passphrase?: string; | ||
| pfx?: Buffer | string; | ||
| cert?: string; | ||
| ca?: string; | ||
| ciphers?: string; | ||
| secureProtocol?: string; | ||
| } | ||
| type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed; | ||
| type ProxyTargetUrl = string | Partial<URL>; | ||
| interface ProxyServerOptions { | ||
| /** URL string to be parsed with the url module. */ | ||
| target?: ProxyTarget; | ||
| /** URL string to be parsed with the url module. */ | ||
| forward?: ProxyTargetUrl; | ||
| /** Object to be passed to http(s).request. */ | ||
| agent?: any; | ||
| /** Object to be passed to https.createServer(). */ | ||
| ssl?: any; | ||
| /** If you want to proxy websockets. */ | ||
| ws?: boolean; | ||
| /** Adds x- forward headers. */ | ||
| xfwd?: boolean; | ||
| /** Verify SSL certificate. */ | ||
| secure?: boolean; | ||
| /** Explicitly specify if we are proxying to another proxy. */ | ||
| toProxy?: boolean; | ||
| /** Specify whether you want to prepend the target's path to the proxy path. */ | ||
| prependPath?: boolean; | ||
| /** Specify whether you want to ignore the proxy path of the incoming request. */ | ||
| ignorePath?: boolean; | ||
| /** Local interface string to bind for outgoing connections. */ | ||
| localAddress?: string; | ||
| /** Changes the origin of the host header to the target URL. */ | ||
| changeOrigin?: boolean; | ||
| /** specify whether you want to keep letter case of response header key */ | ||
| preserveHeaderKeyCase?: boolean; | ||
| /** Basic authentication i.e. 'user:password' to compute an Authorization header. */ | ||
| auth?: string; | ||
| /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */ | ||
| hostRewrite?: string; | ||
| /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */ | ||
| autoRewrite?: boolean; | ||
| /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */ | ||
| protocolRewrite?: string; | ||
| /** Rewrites domain of set-cookie headers. */ | ||
| cookieDomainRewrite?: false | string | { | ||
| [oldDomain: string]: string; | ||
| }; | ||
| /** Rewrites path of set-cookie headers. Default: false */ | ||
| cookiePathRewrite?: false | string | { | ||
| [oldPath: string]: string; | ||
| }; | ||
| /** Object with extra headers to be added to target requests. */ | ||
| headers?: { | ||
| [header: string]: string; | ||
| }; | ||
| /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */ | ||
| proxyTimeout?: number; | ||
| /** Timeout (in milliseconds) for incoming requests */ | ||
| timeout?: number; | ||
| /** If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event */ | ||
| selfHandleResponse?: boolean; | ||
| /** Buffer */ | ||
| buffer?: stream.Stream; | ||
| } | ||
| //#endregion | ||
| export { ProxyServerOptions as t }; |
| //#region node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.d.mts | ||
| interface SourceMapOptions { | ||
| /** | ||
| * Whether the mapping should be high-resolution. | ||
| * Hi-res mappings map every single character, meaning (for example) your devtools will always | ||
| * be able to pinpoint the exact location of function calls and so on. | ||
| * With lo-res mappings, devtools may only be able to identify the correct | ||
| * line - but they're quicker to generate and less bulky. | ||
| * You can also set `"boundary"` to generate a semi-hi-res mappings segmented per word boundary | ||
| * instead of per character, suitable for string semantics that are separated by words. | ||
| * If sourcemap locations have been specified with s.addSourceMapLocation(), they will be used here. | ||
| */ | ||
| hires?: boolean | 'boundary'; | ||
| /** | ||
| * The filename where you plan to write the sourcemap. | ||
| */ | ||
| file?: string; | ||
| /** | ||
| * The filename of the file containing the original source. | ||
| */ | ||
| source?: string; | ||
| /** | ||
| * Whether to include the original content in the map's sourcesContent array. | ||
| */ | ||
| includeContent?: boolean; | ||
| } | ||
| type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; | ||
| interface DecodedSourceMap { | ||
| file: string; | ||
| sources: string[]; | ||
| sourcesContent?: string[]; | ||
| names: string[]; | ||
| mappings: SourceMapSegment[][]; | ||
| x_google_ignoreList?: number[]; | ||
| } | ||
| declare class SourceMap { | ||
| constructor(properties: DecodedSourceMap); | ||
| version: number; | ||
| file: string; | ||
| sources: string[]; | ||
| sourcesContent?: string[]; | ||
| names: string[]; | ||
| mappings: string; | ||
| x_google_ignoreList?: number[]; | ||
| debugId?: string; | ||
| /** | ||
| * Returns the equivalent of `JSON.stringify(map)` | ||
| */ | ||
| toString(): string; | ||
| /** | ||
| * Returns a DataURI containing the sourcemap. Useful for doing this sort of thing: | ||
| * `generateMap(options?: SourceMapOptions): SourceMap;` | ||
| */ | ||
| toUrl(): string; | ||
| } | ||
| type ExclusionRange = [number, number]; | ||
| interface MagicStringOptions { | ||
| filename?: string; | ||
| indentExclusionRanges?: ExclusionRange | Array<ExclusionRange>; | ||
| offset?: number; | ||
| } | ||
| interface IndentOptions { | ||
| exclude?: ExclusionRange | Array<ExclusionRange>; | ||
| indentStart?: boolean; | ||
| } | ||
| interface OverwriteOptions { | ||
| storeName?: boolean; | ||
| contentOnly?: boolean; | ||
| } | ||
| interface UpdateOptions { | ||
| storeName?: boolean; | ||
| overwrite?: boolean; | ||
| } | ||
| declare class MagicString { | ||
| constructor(str: string, options?: MagicStringOptions); | ||
| /** | ||
| * Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is false. | ||
| */ | ||
| addSourcemapLocation(char: number): void; | ||
| /** | ||
| * Appends the specified content to the end of the string. | ||
| */ | ||
| append(content: string): this; | ||
| /** | ||
| * Appends the specified content at the index in the original string. | ||
| * If a range *ending* with index is subsequently moved, the insert will be moved with it. | ||
| * See also `s.prependLeft(...)`. | ||
| */ | ||
| appendLeft(index: number, content: string): this; | ||
| /** | ||
| * Appends the specified content at the index in the original string. | ||
| * If a range *starting* with index is subsequently moved, the insert will be moved with it. | ||
| * See also `s.prependRight(...)`. | ||
| */ | ||
| appendRight(index: number, content: string): this; | ||
| /** | ||
| * Does what you'd expect. | ||
| */ | ||
| clone(): this; | ||
| /** | ||
| * Generates a version 3 sourcemap. | ||
| */ | ||
| generateMap(options?: SourceMapOptions): SourceMap; | ||
| /** | ||
| * Generates a sourcemap object with raw mappings in array form, rather than encoded as a string. | ||
| * Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead. | ||
| */ | ||
| generateDecodedMap(options?: SourceMapOptions): DecodedSourceMap; | ||
| getIndentString(): string; | ||
| /** | ||
| * Prefixes each line of the string with prefix. | ||
| * If prefix is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. | ||
| */ | ||
| indent(options?: IndentOptions): this; | ||
| /** | ||
| * Prefixes each line of the string with prefix. | ||
| * If prefix is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. | ||
| * | ||
| * The options argument can have an exclude property, which is an array of [start, end] character ranges. | ||
| * These ranges will be excluded from the indentation - useful for (e.g.) multiline strings. | ||
| */ | ||
| indent(indentStr?: string, options?: IndentOptions): this; | ||
| indentExclusionRanges: ExclusionRange | Array<ExclusionRange>; | ||
| /** | ||
| * Moves the characters from `start` and `end` to `index`. | ||
| */ | ||
| move(start: number, end: number, index: number): this; | ||
| /** | ||
| * Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in | ||
| * that range. The same restrictions as `s.remove()` apply. | ||
| * | ||
| * The fourth argument is optional. It can have a storeName property — if true, the original name will be stored | ||
| * for later inclusion in a sourcemap's names array — and a contentOnly property which determines whether only | ||
| * the content is overwritten, or anything that was appended/prepended to the range as well. | ||
| * | ||
| * It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content. | ||
| */ | ||
| overwrite(start: number, end: number, content: string, options?: boolean | OverwriteOptions): this; | ||
| /** | ||
| * Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply. | ||
| * | ||
| * The fourth argument is optional. It can have a storeName property — if true, the original name will be stored | ||
| * for later inclusion in a sourcemap's names array — and an overwrite property which determines whether only | ||
| * the content is overwritten, or anything that was appended/prepended to the range as well. | ||
| */ | ||
| update(start: number, end: number, content: string, options?: boolean | UpdateOptions): this; | ||
| /** | ||
| * Prepends the string with the specified content. | ||
| */ | ||
| prepend(content: string): this; | ||
| /** | ||
| * Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index | ||
| */ | ||
| prependLeft(index: number, content: string): this; | ||
| /** | ||
| * Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index` | ||
| */ | ||
| prependRight(index: number, content: string): this; | ||
| /** | ||
| * Removes the characters from `start` to `end` (of the original string, **not** the generated string). | ||
| * Removing the same content twice, or making removals that partially overlap, will cause an error. | ||
| */ | ||
| remove(start: number, end: number): this; | ||
| /** | ||
| * Reset the modified characters from `start` to `end` (of the original string, **not** the generated string). | ||
| */ | ||
| reset(start: number, end: number): this; | ||
| /** | ||
| * Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string. | ||
| * Throws error if the indices are for characters that were already removed. | ||
| */ | ||
| slice(start: number, end: number): string; | ||
| /** | ||
| * Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed. | ||
| */ | ||
| snip(start: number, end: number): this; | ||
| /** | ||
| * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end. | ||
| */ | ||
| trim(charType?: string): this; | ||
| /** | ||
| * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start. | ||
| */ | ||
| trimStart(charType?: string): this; | ||
| /** | ||
| * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end. | ||
| */ | ||
| trimEnd(charType?: string): this; | ||
| /** | ||
| * Removes empty lines from the start and end. | ||
| */ | ||
| trimLines(): this; | ||
| /** | ||
| * String replacement with RegExp or string. | ||
| */ | ||
| replace(regex: RegExp | string, replacement: string | ((substring: string, ...args: any[]) => string)): this; | ||
| /** | ||
| * Same as `s.replace`, but replace all matched strings instead of just one. | ||
| */ | ||
| replaceAll(regex: RegExp | string, replacement: string | ((substring: string, ...args: any[]) => string)): this; | ||
| lastChar(): string; | ||
| lastLine(): string; | ||
| /** | ||
| * Returns true if the resulting source is empty (disregarding white space). | ||
| */ | ||
| isEmpty(): boolean; | ||
| length(): number; | ||
| /** | ||
| * Indicates if the string has been changed. | ||
| */ | ||
| hasChanged(): boolean; | ||
| original: string; | ||
| /** | ||
| * Returns the generated string. | ||
| */ | ||
| toString(): string; | ||
| offset: number; | ||
| } | ||
| //#endregion | ||
| export { MagicString as t }; |
| //#region node_modules/.pnpm/mlly@1.8.0/node_modules/mlly/dist/index.d.ts | ||
| /** | ||
| * Represents a general structure for ECMAScript module exports. | ||
| */ | ||
| interface ESMExport { | ||
| /** | ||
| * Optional explicit type for complex scenarios, often used internally. | ||
| * @optional | ||
| */ | ||
| _type?: "declaration" | "named" | "default" | "star"; | ||
| /** | ||
| * The type of export (declaration, named, default or star). | ||
| */ | ||
| type: "declaration" | "named" | "default" | "star"; | ||
| /** | ||
| * The specific type of declaration being exported, if applicable. | ||
| * @optional | ||
| */ | ||
| declarationType?: "let" | "var" | "const" | "enum" | "const enum" | "class" | "function" | "async function"; | ||
| /** | ||
| * The full code snippet of the export statement. | ||
| */ | ||
| code: string; | ||
| /** | ||
| * The starting position (index) of the export declaration in the source code. | ||
| */ | ||
| start: number; | ||
| /** | ||
| * The end position (index) of the export declaration in the source code. | ||
| */ | ||
| end: number; | ||
| /** | ||
| * The name of the variable, function or class being exported, if given explicitly. | ||
| * @optional | ||
| */ | ||
| name?: string; | ||
| /** | ||
| * The name used for default exports when a specific identifier isn't given. | ||
| * @optional | ||
| */ | ||
| defaultName?: string; | ||
| /** | ||
| * An array of names to export, applicable to named and destructured exports. | ||
| */ | ||
| names: string[]; | ||
| /** | ||
| * The module specifier, if any, from which exports are being re-exported. | ||
| * @optional | ||
| */ | ||
| specifier?: string; | ||
| } | ||
| /** | ||
| * Represents a declaration export within an ECMAScript module. | ||
| * Extends {@link ESMExport}. | ||
| */ | ||
| //#endregion | ||
| export { ESMExport as t }; |
Sorry, the diff of this file is too big to display
| import { CompilerOptions, TypeAcquisition } from "typescript"; | ||
| //#region node_modules/.pnpm/pkg-types@2.3.0/node_modules/pkg-types/dist/index.d.mts | ||
| type StripEnums<T extends Record<string, any>> = { [K in keyof T]: T[K] extends boolean ? T[K] : T[K] extends string ? T[K] : T[K] extends object ? T[K] : T[K] extends Array<any> ? T[K] : T[K] extends undefined ? undefined : any }; | ||
| interface TSConfig { | ||
| compilerOptions?: StripEnums<CompilerOptions>; | ||
| exclude?: string[]; | ||
| compileOnSave?: boolean; | ||
| extends?: string | string[]; | ||
| files?: string[]; | ||
| include?: string[]; | ||
| typeAcquisition?: TypeAcquisition; | ||
| references?: { | ||
| path: string; | ||
| }[]; | ||
| } | ||
| /** | ||
| * Defines a TSConfig structure. | ||
| * @param tsconfig - The contents of `tsconfig.json` as an object. See {@link TSConfig}. | ||
| * @returns the same `tsconfig.json` object. | ||
| */ | ||
| //#endregion | ||
| export { TSConfig as t }; |
| import { n as __exportAll } from "../_common.mjs"; | ||
| import { S as MagicString, x as stripLiteral } from "../_build/common.mjs"; | ||
| import fs from "node:fs"; | ||
| import { fileURLToPath } from "node:url"; | ||
| import path from "node:path"; | ||
| import assert from "node:assert"; | ||
| import { createHash } from "node:crypto"; | ||
| import { isCSSRequest, normalizePath } from "vite"; | ||
| import assert$1 from "node:assert/strict"; | ||
| //#region node_modules/.pnpm/@rolldown+pluginutils@1.0.0-beta.55/node_modules/@rolldown/pluginutils/dist/simple-filters.js | ||
| /** | ||
| * Constructs a RegExp that matches the exact string specified. | ||
| * | ||
| * This is useful for plugin hook filters. | ||
| * | ||
| * @param str the string to match. | ||
| * @param flags flags for the RegExp. | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * import { exactRegex } from '@rolldown/pluginutils'; | ||
| * const plugin = { | ||
| * name: 'plugin', | ||
| * resolveId: { | ||
| * filter: { id: exactRegex('foo') }, | ||
| * handler(id) {} // will only be called for `foo` | ||
| * } | ||
| * } | ||
| * ``` | ||
| */ | ||
| function exactRegex(str, flags) { | ||
| return new RegExp(`^${escapeRegex(str)}$`, flags); | ||
| } | ||
| const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g; | ||
| function escapeRegex(str) { | ||
| return str.replace(escapeRegexRE, "\\$&"); | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/@hiogawa+vite-plugin-fullstack@0.0.11_vite@8.0.0-beta.8_@types+node@25.0.9_esbuild@0.27_577572ae8fc6296e77b8a4205393d7c0/node_modules/@hiogawa/vite-plugin-fullstack/dist/plugin-B4MlD0Bd.js | ||
| function parseIdQuery(id) { | ||
| if (!id.includes("?")) return { | ||
| filename: id, | ||
| query: {} | ||
| }; | ||
| const [filename, rawQuery] = id.split(`?`, 2); | ||
| return { | ||
| filename, | ||
| query: Object.fromEntries(new URLSearchParams(rawQuery)) | ||
| }; | ||
| } | ||
| function toAssetsVirtual(options) { | ||
| return `virtual:fullstack/assets?${new URLSearchParams(options)}&lang.js`; | ||
| } | ||
| function parseAssetsVirtual(id) { | ||
| if (id.startsWith("\0virtual:fullstack/assets?")) return parseIdQuery(id).query; | ||
| } | ||
| function createVirtualPlugin(name, load) { | ||
| name = "virtual:" + name; | ||
| return { | ||
| name: `fullstack:virtual-${name}`, | ||
| resolveId: { | ||
| filter: { id: exactRegex(name) }, | ||
| handler(source, _importer, _options) { | ||
| return source === name ? "\0" + name : void 0; | ||
| } | ||
| }, | ||
| load: { | ||
| filter: { id: exactRegex("\0" + name) }, | ||
| handler(id, options) { | ||
| return load.apply(this, [id, options]); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function normalizeRelativePath(s) { | ||
| s = normalizePath(s); | ||
| return s[0] === "." ? s : "./" + s; | ||
| } | ||
| function hashString(v) { | ||
| return createHash("sha256").update(v).digest().toString("hex").slice(0, 12); | ||
| } | ||
| const VALID_ID_PREFIX = `/@id/`; | ||
| const NULL_BYTE_PLACEHOLDER = `__x00__`; | ||
| const FS_PREFIX = `/@fs/`; | ||
| function wrapId(id) { | ||
| return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER); | ||
| } | ||
| function withTrailingSlash(path$1) { | ||
| if (path$1[path$1.length - 1] !== "/") return `${path$1}/`; | ||
| return path$1; | ||
| } | ||
| const postfixRE = /[?#].*$/; | ||
| function cleanUrl(url) { | ||
| return url.replace(postfixRE, ""); | ||
| } | ||
| function splitFileAndPostfix(path$1) { | ||
| const file = cleanUrl(path$1); | ||
| return { | ||
| file, | ||
| postfix: path$1.slice(file.length) | ||
| }; | ||
| } | ||
| const windowsSlashRE = /\\/g; | ||
| function slash(p) { | ||
| return p.replace(windowsSlashRE, "/"); | ||
| } | ||
| const isWindows = typeof process !== "undefined" && process.platform === "win32"; | ||
| function injectQuery(url, queryToInject) { | ||
| const { file, postfix } = splitFileAndPostfix(url); | ||
| return `${isWindows ? slash(file) : file}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : postfix}`; | ||
| } | ||
| function normalizeResolvedIdToUrl(environment, url, resolved) { | ||
| const root = environment.config.root; | ||
| const depsOptimizer = environment.depsOptimizer; | ||
| if (resolved.id.startsWith(withTrailingSlash(root))) url = resolved.id.slice(root.length); | ||
| else if (depsOptimizer?.isOptimizedDepFile(resolved.id) || resolved.id !== "/@react-refresh" && path.isAbsolute(resolved.id) && fs.existsSync(cleanUrl(resolved.id))) url = path.posix.join(FS_PREFIX, resolved.id); | ||
| else url = resolved.id; | ||
| if (url[0] !== "." && url[0] !== "/") url = wrapId(resolved.id); | ||
| return url; | ||
| } | ||
| function normalizeViteImportAnalysisUrl(environment, id) { | ||
| let url = normalizeResolvedIdToUrl(environment, id, { id }); | ||
| if (environment.config.consumer === "client") { | ||
| const mod = environment.moduleGraph.getModuleById(id); | ||
| if (mod && mod.lastHMRTimestamp > 0) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`); | ||
| } | ||
| return url; | ||
| } | ||
| function evalValue(rawValue) { | ||
| return new Function(` | ||
| var console, exports, global, module, process, require | ||
| return (\n${rawValue}\n) | ||
| `)(); | ||
| } | ||
| const directRequestRE = /(\?|&)direct=?(?:&|$)/; | ||
| function assetsPlugin(pluginOpts) { | ||
| let server; | ||
| let resolvedConfig; | ||
| const importAssetsMetaMap = {}; | ||
| const bundleMap = {}; | ||
| async function processAssetsImport(ctx, id, options) { | ||
| if (ctx.environment.mode === "dev") { | ||
| const result = { | ||
| entry: void 0, | ||
| js: [], | ||
| css: [] | ||
| }; | ||
| const environment = server.environments[options.environment]; | ||
| assert$1(environment, `Unknown environment: ${options.environment}`); | ||
| if (options.environment === "client") result.entry = assetsURLDev(normalizeViteImportAnalysisUrl(environment, id).slice(1), resolvedConfig); | ||
| if (environment.name !== "client") { | ||
| const collected = await collectCss(environment, id, { eager: pluginOpts?.experimental?.devEagerTransform ?? true }); | ||
| result.css = collected.hrefs.map((href, i) => ({ | ||
| href: assetsURLDev(href.slice(1), resolvedConfig), | ||
| "data-vite-dev-id": collected.ids[i] | ||
| })); | ||
| } | ||
| return JSON.stringify(result); | ||
| } else { | ||
| const map = importAssetsMetaMap[options.environment] ??= {}; | ||
| const meta = { | ||
| id, | ||
| key: path.relative(resolvedConfig.root, id), | ||
| importerEnvironment: ctx.environment.name, | ||
| isEntry: !!(map[id]?.isEntry || options.isEntry) | ||
| }; | ||
| map[id] = meta; | ||
| return `__assets_manifest[${JSON.stringify(options.environment)}][${JSON.stringify(meta.key)}]`; | ||
| } | ||
| } | ||
| let writeAssetsManifestCalled = false; | ||
| async function writeAssetsManifest(builder) { | ||
| if (writeAssetsManifestCalled) return; | ||
| writeAssetsManifestCalled = true; | ||
| const manifest = {}; | ||
| for (const [environmentName, metas] of Object.entries(importAssetsMetaMap)) { | ||
| const bundle = bundleMap[environmentName]; | ||
| const assetDepsMap = collectAssetDeps(bundle); | ||
| for (const [id, meta] of Object.entries(metas)) { | ||
| const found = assetDepsMap[id]; | ||
| if (!found) { | ||
| builder.config.logger.error(`[vite-plugin-fullstack] failed to find built chunk for ${meta.id} imported by ${meta.importerEnvironment} environment`); | ||
| return; | ||
| } | ||
| const result = { | ||
| js: [], | ||
| css: [] | ||
| }; | ||
| const { chunk, deps } = found; | ||
| if (environmentName === "client") { | ||
| result.entry = assetsURL(chunk.fileName, builder.config); | ||
| result.js = deps.js.map((fileName) => ({ href: assetsURL(fileName, builder.config) })); | ||
| } | ||
| result.css = deps.css.map((fileName) => ({ href: assetsURL(fileName, builder.config) })); | ||
| if (!builder.environments[environmentName].config.build.cssCodeSplit) { | ||
| const singleCss = Object.values(bundle).find((v) => v.type === "asset" && v.originalFileNames.includes("style.css")); | ||
| if (singleCss) result.css.push({ href: assetsURL(singleCss.fileName, builder.config) }); | ||
| } | ||
| (manifest[environmentName] ??= {})[meta.key] = result; | ||
| } | ||
| } | ||
| const importerEnvironments = new Set(Object.values(importAssetsMetaMap).flatMap((metas) => Object.values(metas)).flatMap((meta) => meta.importerEnvironment)); | ||
| for (const environmentName of importerEnvironments) { | ||
| const outDir = builder.environments[environmentName].config.build.outDir; | ||
| fs.writeFileSync(path.join(outDir, BUILD_ASSETS_MANIFEST_NAME), `export default ${serializeValueWithRuntime(manifest)};`); | ||
| const clientOutDir = builder.environments["client"].config.build.outDir; | ||
| for (const asset of Object.values(bundleMap[environmentName])) if (asset.type === "asset") { | ||
| const srcFile = path.join(outDir, asset.fileName); | ||
| const destFile = path.join(clientOutDir, asset.fileName); | ||
| fs.mkdirSync(path.dirname(destFile), { recursive: true }); | ||
| fs.copyFileSync(srcFile, destFile); | ||
| } | ||
| } | ||
| } | ||
| return [ | ||
| { | ||
| name: "fullstack:assets", | ||
| sharedDuringBuild: true, | ||
| configureServer(server_) { | ||
| server = server_; | ||
| }, | ||
| configResolved(config) { | ||
| resolvedConfig = config; | ||
| }, | ||
| configEnvironment(name) { | ||
| if ((pluginOpts?.serverEnvironments ?? ["ssr"]).includes(name)) return { build: { emitAssets: true } }; | ||
| }, | ||
| transform: { | ||
| filter: { code: /import\.meta\.vite\.assets\(/ }, | ||
| async handler(code, id, _options) { | ||
| const output = new MagicString(code); | ||
| const strippedCode = stripLiteral(code); | ||
| const newImports = /* @__PURE__ */ new Set(); | ||
| for (const match of code.matchAll(/import\.meta\.vite\.assets\(([\s\S]*?)\)/dg)) { | ||
| const [start, end] = match.indices[0]; | ||
| if (!strippedCode.slice(start, end).includes("import.meta.vite.assets")) continue; | ||
| if (this.environment.name === "client") { | ||
| const replacement$1 = `(${JSON.stringify(EMPTY_ASSETS)})`; | ||
| output.update(start, end, replacement$1); | ||
| continue; | ||
| } | ||
| const argCode = match[1].trim(); | ||
| const options = { | ||
| import: id, | ||
| environment: void 0, | ||
| asEntry: false | ||
| }; | ||
| if (argCode) { | ||
| const argValue = evalValue(argCode); | ||
| Object.assign(options, argValue); | ||
| } | ||
| const environments = options.environment ? [options.environment] : ["client", this.environment.name]; | ||
| const importedNames = []; | ||
| for (const environment of environments) { | ||
| const importSource = toAssetsVirtual({ | ||
| import: options.import, | ||
| importer: id, | ||
| environment, | ||
| entry: options.asEntry ? "1" : "" | ||
| }); | ||
| const importedName = `__assets_${hashString(importSource)}`; | ||
| newImports.add(`;import ${importedName} from ${JSON.stringify(importSource)};\n`); | ||
| importedNames.push(importedName); | ||
| } | ||
| let replacement = importedNames[0]; | ||
| if (importedNames.length > 1) { | ||
| newImports.add(`;import * as __assets_runtime from "virtual:fullstack/runtime";\n`); | ||
| replacement = `__assets_runtime.mergeAssets(${importedNames.join(", ")})`; | ||
| } | ||
| output.update(start, end, `(${replacement})`); | ||
| } | ||
| if (output.hasChanged()) { | ||
| for (const newImport of newImports) output.append(newImport); | ||
| return { | ||
| code: output.toString(), | ||
| map: output.generateMap({ hires: "boundary" }) | ||
| }; | ||
| } | ||
| } | ||
| }, | ||
| resolveId: { | ||
| filter: { id: /^virtual:fullstack\// }, | ||
| handler(source) { | ||
| if (source === "virtual:fullstack/runtime") return "\0" + source; | ||
| if (source.startsWith("virtual:fullstack/assets?")) return "\0" + source; | ||
| if (source === "virtual:fullstack/assets-manifest") { | ||
| assert$1.notEqual(this.environment.name, "client"); | ||
| assert$1.equal(this.environment.mode, "build"); | ||
| return { | ||
| id: source, | ||
| external: true | ||
| }; | ||
| } | ||
| } | ||
| }, | ||
| load: { | ||
| filter: { id: /^\0virtual:fullstack\// }, | ||
| async handler(id) { | ||
| if (id === "\0virtual:fullstack/runtime") return `export const mergeAssets = ${(await Promise.resolve().then(() => runtime_exports)).mergeAssets.toString()};`; | ||
| const parsed = parseAssetsVirtual(id); | ||
| if (!parsed) return; | ||
| assert$1.notEqual(this.environment.name, "client"); | ||
| const resolved = await this.resolve(parsed.import, parsed.importer); | ||
| assert$1(resolved, `Failed to resolve: ${parsed.import}`); | ||
| const s = new MagicString(""); | ||
| const code = await processAssetsImport(this, resolved.id, { | ||
| environment: parsed.environment, | ||
| isEntry: !!parsed.entry | ||
| }); | ||
| s.append(`export default ${code};\n`); | ||
| if (this.environment.mode === "build") s.prepend(`import __assets_manifest from "virtual:fullstack/assets-manifest";\n`); | ||
| return s.toString(); | ||
| } | ||
| }, | ||
| renderChunk(code, chunk) { | ||
| if (code.includes("virtual:fullstack/assets-manifest")) { | ||
| const replacement = normalizeRelativePath(path.relative(path.join(chunk.fileName, ".."), BUILD_ASSETS_MANIFEST_NAME)); | ||
| code = code.replaceAll("virtual:fullstack/assets-manifest", () => replacement); | ||
| return { code }; | ||
| } | ||
| }, | ||
| writeBundle(_options, bundle) { | ||
| bundleMap[this.environment.name] = bundle; | ||
| }, | ||
| buildStart() { | ||
| if (this.environment.mode == "build" && this.environment.name === "client") { | ||
| if (importAssetsMetaMap["client"]) { | ||
| for (const meta of Object.values(importAssetsMetaMap["client"])) if (meta.isEntry) this.emitFile({ | ||
| type: "chunk", | ||
| id: meta.id, | ||
| preserveSignature: "exports-only" | ||
| }); | ||
| } | ||
| } | ||
| }, | ||
| buildApp: { | ||
| order: "pre", | ||
| async handler(builder) { | ||
| builder.writeAssetsManifest = async () => { | ||
| await writeAssetsManifest(builder); | ||
| }; | ||
| } | ||
| } | ||
| }, | ||
| { | ||
| name: "fullstack:write-assets-manifest-post", | ||
| buildApp: { | ||
| order: "post", | ||
| async handler(builder) { | ||
| await builder.writeAssetsManifest(); | ||
| } | ||
| } | ||
| }, | ||
| { | ||
| name: "fullstack:assets-query", | ||
| sharedDuringBuild: true, | ||
| resolveId: { | ||
| order: "pre", | ||
| filter: { id: /[?&]assets/ }, | ||
| handler(source) { | ||
| const { query } = parseIdQuery(source); | ||
| if (typeof query["assets"] !== "undefined") { | ||
| if (this.environment.name === "client") return `\0virtual:fullstack/empty-assets`; | ||
| } | ||
| } | ||
| }, | ||
| load: { | ||
| filter: { id: [/^\0virtual:fullstack\/empty-assets$/, /[?&]assets/] }, | ||
| async handler(id) { | ||
| if (id === "\0virtual:fullstack/empty-assets") return `export default ${JSON.stringify(EMPTY_ASSETS)}`; | ||
| const { filename, query } = parseIdQuery(id); | ||
| const value = query["assets"]; | ||
| if (typeof value !== "undefined") { | ||
| const s = new MagicString(""); | ||
| const codes = []; | ||
| if (value) { | ||
| const code = await processAssetsImport(this, filename, { | ||
| environment: value, | ||
| isEntry: value === "client" | ||
| }); | ||
| codes.push(code); | ||
| } else { | ||
| const code1 = await processAssetsImport(this, filename, { | ||
| environment: "client", | ||
| isEntry: false | ||
| }); | ||
| const code2 = await processAssetsImport(this, filename, { | ||
| environment: this.environment.name, | ||
| isEntry: false | ||
| }); | ||
| codes.push(code1, code2); | ||
| } | ||
| s.append(` | ||
| import * as __assets_runtime from "virtual:fullstack/runtime";\n | ||
| export default __assets_runtime.mergeAssets(${codes.join(", ")}); | ||
| `); | ||
| if (this.environment.mode === "build") s.prepend(`import __assets_manifest from "virtual:fullstack/assets-manifest";\n`); | ||
| return { | ||
| code: s.toString(), | ||
| moduleSideEffects: false | ||
| }; | ||
| } | ||
| } | ||
| }, | ||
| hotUpdate(ctx) { | ||
| if (this.environment.name === "rsc") { | ||
| const mods = collectModuleDependents(ctx.modules); | ||
| for (const mod of mods) if (mod.id) { | ||
| const ids = [ | ||
| `${mod.id}?assets`, | ||
| `${mod.id}?assets=client`, | ||
| `${mod.id}?assets=${this.environment.name}` | ||
| ]; | ||
| for (const id of ids) invalidteModuleById(this.environment, id); | ||
| } | ||
| } | ||
| } | ||
| }, | ||
| { | ||
| ...createVirtualPlugin("fullstack/client-fallback", () => "export {}"), | ||
| configEnvironment: { | ||
| order: "post", | ||
| handler(name, config, _env) { | ||
| if (name === "client") { | ||
| if ((pluginOpts?.experimental?.clientBuildFallback ?? true) && !config.build?.rollupOptions?.input) return { build: { rollupOptions: { input: { __fallback: "virtual:fullstack/client-fallback" } } } }; | ||
| } | ||
| } | ||
| }, | ||
| generateBundle(_optoins, bundle) { | ||
| if (this.environment.name !== "client") return; | ||
| for (const [k, v] of Object.entries(bundle)) if (v.type === "chunk" && v.name === "__fallback") delete bundle[k]; | ||
| } | ||
| }, | ||
| patchViteClientPlugin(), | ||
| patchVueScopeCssHmr(), | ||
| patchCssLinkSelfAccept() | ||
| ]; | ||
| } | ||
| const EMPTY_ASSETS = { | ||
| js: [], | ||
| css: [] | ||
| }; | ||
| const BUILD_ASSETS_MANIFEST_NAME = "__fullstack_assets_manifest.js"; | ||
| async function collectCss(environment, entryId, options) { | ||
| const visited = /* @__PURE__ */ new Set(); | ||
| const cssIds = /* @__PURE__ */ new Set(); | ||
| async function recurse(id) { | ||
| if (visited.has(id) || parseAssetsVirtual(id) || "assets" in parseIdQuery(id).query) return; | ||
| visited.add(id); | ||
| const mod = environment.moduleGraph.getModuleById(id); | ||
| if (!mod) return; | ||
| if (options.eager && !mod?.transformResult) try { | ||
| await environment.transformRequest(id); | ||
| } catch (e) { | ||
| console.error(`[collectCss] Failed to transform '${id}'`, e); | ||
| } | ||
| for (const next of mod?.importedModules ?? []) if (next.id) if (isCSSRequest(next.id)) { | ||
| if (hasSpecialCssQuery(next.id)) continue; | ||
| cssIds.add(next.id); | ||
| } else await recurse(next.id); | ||
| } | ||
| await recurse(entryId); | ||
| const hrefs = [...cssIds].map((id) => normalizeViteImportAnalysisUrl(environment, id)); | ||
| return { | ||
| ids: [...cssIds], | ||
| hrefs | ||
| }; | ||
| } | ||
| function invalidteModuleById(environment, id) { | ||
| const mod = environment.moduleGraph.getModuleById(id); | ||
| if (mod) environment.moduleGraph.invalidateModule(mod); | ||
| return mod; | ||
| } | ||
| function collectModuleDependents(mods) { | ||
| const visited = /* @__PURE__ */ new Set(); | ||
| function recurse(mod) { | ||
| if (visited.has(mod)) return; | ||
| visited.add(mod); | ||
| for (const importer of mod.importers) recurse(importer); | ||
| } | ||
| for (const mod of mods) recurse(mod); | ||
| return [...visited]; | ||
| } | ||
| function hasSpecialCssQuery(id) { | ||
| return /[?&](url|inline|raw)(\b|=|&|$)/.test(id); | ||
| } | ||
| function collectAssetDeps(bundle) { | ||
| const chunkToDeps = /* @__PURE__ */ new Map(); | ||
| for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") chunkToDeps.set(chunk, collectAssetDepsInner(chunk.fileName, bundle)); | ||
| const idToDeps = {}; | ||
| for (const [chunk, deps] of chunkToDeps.entries()) for (const id of chunk.moduleIds) idToDeps[id] = { | ||
| chunk, | ||
| deps | ||
| }; | ||
| return idToDeps; | ||
| } | ||
| function collectAssetDepsInner(fileName, bundle) { | ||
| const visited = /* @__PURE__ */ new Set(); | ||
| const css = []; | ||
| function recurse(k) { | ||
| if (visited.has(k)) return; | ||
| visited.add(k); | ||
| const v = bundle[k]; | ||
| assert$1(v, `Not found '${k}' in the bundle`); | ||
| if (v.type === "chunk") { | ||
| css.push(...v.viteMetadata?.importedCss ?? []); | ||
| for (const k2 of v.imports) if (k2 in bundle) recurse(k2); | ||
| } | ||
| } | ||
| recurse(fileName); | ||
| return { | ||
| js: [...visited], | ||
| css: [...new Set(css)] | ||
| }; | ||
| } | ||
| function patchViteClientPlugin() { | ||
| const viteClientPath = normalizePath(fileURLToPath(import.meta.resolve("vite/dist/client/client.mjs"))); | ||
| function endIndexOf(code, searchValue) { | ||
| const i = code.lastIndexOf(searchValue); | ||
| return i === -1 ? i : i + searchValue.length; | ||
| } | ||
| return { | ||
| name: "fullstack:patch-vite-client", | ||
| transform: { | ||
| filter: { id: exactRegex(viteClientPath) }, | ||
| handler(code, id) { | ||
| if (id === viteClientPath) { | ||
| if (code.includes("linkSheetsMap")) return; | ||
| const s = new MagicString(code); | ||
| s.prependLeft(code.indexOf("const sheetsMap"), `\ | ||
| const linkSheetsMap = new Map(); | ||
| document | ||
| .querySelectorAll('link[rel="stylesheet"][data-vite-dev-id]') | ||
| .forEach((el) => { | ||
| linkSheetsMap.set(el.getAttribute('data-vite-dev-id'), el) | ||
| }); | ||
| `); | ||
| s.appendLeft(endIndexOf(code, `function updateStyle(id, content) {`), `if (linkSheetsMap.has(id)) { return }`); | ||
| s.appendLeft(endIndexOf(code, `function removeStyle(id) {`), ` | ||
| const link = linkSheetsMap.get(id); | ||
| if (link) { | ||
| document | ||
| .querySelectorAll( | ||
| 'link[rel="stylesheet"][data-vite-dev-id]', | ||
| ) | ||
| .forEach((el) => { | ||
| if (el.getAttribute('data-vite-dev-id') === id) { | ||
| el.remove() | ||
| } | ||
| }) | ||
| linkSheetsMap.delete(id) | ||
| } | ||
| `); | ||
| return s.toString(); | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function patchVueScopeCssHmr() { | ||
| return { | ||
| name: "fullstack:patch-vue-scoped-css-hmr", | ||
| configureServer(server) { | ||
| server.middlewares.use((req, _res, next) => { | ||
| if (req.headers.accept?.includes("text/css") && req.url?.includes("&lang.css=")) req.url = req.url.replace("&lang.css=", "?lang.css"); | ||
| next(); | ||
| }); | ||
| } | ||
| }; | ||
| } | ||
| function patchCssLinkSelfAccept() { | ||
| return { | ||
| name: "fullstack:patch-css-link-self-accept", | ||
| apply: "serve", | ||
| transform: { | ||
| order: "post", | ||
| handler(_code, id, _options) { | ||
| if (this.environment.name === "client" && this.environment.mode === "dev" && isCSSRequest(id) && directRequestRE.test(id)) { | ||
| const mod = this.environment.moduleGraph.getModuleById(id); | ||
| if (mod && !mod.isSelfAccepting) mod.isSelfAccepting = true; | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| var BuildAssetsURLWithRuntime = class { | ||
| constructor(runtime) { | ||
| this.runtime = runtime; | ||
| } | ||
| }; | ||
| function serializeValueWithRuntime(value) { | ||
| const replacements = []; | ||
| let result = JSON.stringify(value, (_key, value$1) => { | ||
| if (value$1 instanceof BuildAssetsURLWithRuntime) { | ||
| const placeholder = `__runtime_placeholder_${replacements.length}__`; | ||
| replacements.push([placeholder, value$1.runtime]); | ||
| return placeholder; | ||
| } | ||
| return value$1; | ||
| }, 2); | ||
| for (const [placeholder, runtime] of replacements) result = result.replace(`"${placeholder}"`, runtime); | ||
| return result; | ||
| } | ||
| function assetsURL(url, config) { | ||
| if (config.command === "build" && typeof config.experimental?.renderBuiltUrl === "function") { | ||
| const result = config.experimental.renderBuiltUrl(url, { | ||
| type: "asset", | ||
| hostType: "js", | ||
| ssr: true, | ||
| hostId: "" | ||
| }); | ||
| if (typeof result === "object") { | ||
| if (result.runtime) return new BuildAssetsURLWithRuntime(result.runtime); | ||
| assert$1(!result.relative, "\"result.relative\" not supported on renderBuiltUrl() for fullstack plugin"); | ||
| } else if (result) return result; | ||
| } | ||
| return config.base + url; | ||
| } | ||
| function assetsURLDev(url, config) { | ||
| return config.base + url; | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/@hiogawa+vite-plugin-fullstack@0.0.11_vite@8.0.0-beta.8_@types+node@25.0.9_esbuild@0.27_577572ae8fc6296e77b8a4205393d7c0/node_modules/@hiogawa/vite-plugin-fullstack/dist/runtime.js | ||
| var runtime_exports = /* @__PURE__ */ __exportAll({ mergeAssets: () => mergeAssets }); | ||
| function mergeAssets(...args) { | ||
| const js = uniqBy(args.flatMap((h) => h.js), (a) => a.href); | ||
| const css = uniqBy(args.flatMap((h) => h.css), (a) => a.href); | ||
| const raw = { | ||
| entry: args.filter((arg) => arg.entry)?.[0]?.entry, | ||
| js, | ||
| css | ||
| }; | ||
| return { | ||
| ...raw, | ||
| merge: (...args$1) => mergeAssets(raw, ...args$1) | ||
| }; | ||
| function uniqBy(array, key) { | ||
| const seen = /* @__PURE__ */ new Set(); | ||
| return array.filter((item) => { | ||
| const k = key(item); | ||
| if (seen.has(k)) return false; | ||
| seen.add(k); | ||
| return true; | ||
| }); | ||
| } | ||
| } | ||
| //#endregion | ||
| export { assetsPlugin as n, runtime_exports as t }; |
| import { Plugin } from "rollup"; | ||
| //#region node_modules/.pnpm/@rollup+pluginutils@5.3.0_rollup@4.55.3/node_modules/@rollup/pluginutils/types/index.d.ts | ||
| /** | ||
| * A valid `picomatch` glob pattern, or array of patterns. | ||
| */ | ||
| type FilterPattern = ReadonlyArray<string | RegExp> | string | RegExp | null; | ||
| //#endregion | ||
| //#region node_modules/.pnpm/@rollup+plugin-commonjs@29.0.0_rollup@4.55.3/node_modules/@rollup/plugin-commonjs/types/index.d.ts | ||
| type RequireReturnsDefaultOption = boolean | 'auto' | 'preferred' | 'namespace'; | ||
| type DefaultIsModuleExportsOption = boolean | 'auto'; | ||
| interface RollupCommonJSOptions { | ||
| /** | ||
| * A picomatch pattern, or array of patterns, which specifies the files in | ||
| * the build the plugin should operate on. By default, all files with | ||
| * extension `".cjs"` or those in `extensions` are included, but you can | ||
| * narrow this list by only including specific files. These files will be | ||
| * analyzed and transpiled if either the analysis does not find ES module | ||
| * specific statements or `transformMixedEsModules` is `true`. | ||
| * @default undefined | ||
| */ | ||
| include?: FilterPattern; | ||
| /** | ||
| * A picomatch pattern, or array of patterns, which specifies the files in | ||
| * the build the plugin should _ignore_. By default, all files with | ||
| * extensions other than those in `extensions` or `".cjs"` are ignored, but you | ||
| * can exclude additional files. See also the `include` option. | ||
| * @default undefined | ||
| */ | ||
| exclude?: FilterPattern; | ||
| /** | ||
| * For extensionless imports, search for extensions other than .js in the | ||
| * order specified. Note that you need to make sure that non-JavaScript files | ||
| * are transpiled by another plugin first. | ||
| * @default [ '.js' ] | ||
| */ | ||
| extensions?: ReadonlyArray<string>; | ||
| /** | ||
| * If true then uses of `global` won't be dealt with by this plugin | ||
| * @default false | ||
| */ | ||
| ignoreGlobal?: boolean; | ||
| /** | ||
| * If false, skips source map generation for CommonJS modules. This will | ||
| * improve performance. | ||
| * @default true | ||
| */ | ||
| sourceMap?: boolean; | ||
| /** | ||
| * Some `require` calls cannot be resolved statically to be translated to | ||
| * imports. | ||
| * When this option is set to `false`, the generated code will either | ||
| * directly throw an error when such a call is encountered or, when | ||
| * `dynamicRequireTargets` is used, when such a call cannot be resolved with a | ||
| * configured dynamic require target. | ||
| * Setting this option to `true` will instead leave the `require` call in the | ||
| * code or use it as a fallback for `dynamicRequireTargets`. | ||
| * @default false | ||
| */ | ||
| ignoreDynamicRequires?: boolean; | ||
| /** | ||
| * Instructs the plugin whether to enable mixed module transformations. This | ||
| * is useful in scenarios with modules that contain a mix of ES `import` | ||
| * statements and CommonJS `require` expressions. Set to `true` if `require` | ||
| * calls should be transformed to imports in mixed modules, or `false` if the | ||
| * `require` expressions should survive the transformation. The latter can be | ||
| * important if the code contains environment detection, or you are coding | ||
| * for an environment with special treatment for `require` calls such as | ||
| * ElectronJS. See also the `ignore` option. | ||
| * @default false | ||
| */ | ||
| transformMixedEsModules?: boolean; | ||
| /** | ||
| * By default, this plugin will try to hoist `require` statements as imports | ||
| * to the top of each file. While this works well for many code bases and | ||
| * allows for very efficient ESM output, it does not perfectly capture | ||
| * CommonJS semantics as the order of side effects like log statements may | ||
| * change. But it is especially problematic when there are circular `require` | ||
| * calls between CommonJS modules as those often rely on the lazy execution of | ||
| * nested `require` calls. | ||
| * | ||
| * Setting this option to `true` will wrap all CommonJS files in functions | ||
| * which are executed when they are required for the first time, preserving | ||
| * NodeJS semantics. Note that this can have an impact on the size and | ||
| * performance of the generated code. | ||
| * | ||
| * The default value of `"auto"` will only wrap CommonJS files when they are | ||
| * part of a CommonJS dependency cycle, e.g. an index file that is required by | ||
| * many of its dependencies. All other CommonJS files are hoisted. This is the | ||
| * recommended setting for most code bases. | ||
| * | ||
| * `false` will entirely prevent wrapping and hoist all files. This may still | ||
| * work depending on the nature of cyclic dependencies but will often cause | ||
| * problems. | ||
| * | ||
| * You can also provide a picomatch pattern, or array of patterns, to only | ||
| * specify a subset of files which should be wrapped in functions for proper | ||
| * `require` semantics. | ||
| * | ||
| * `"debug"` works like `"auto"` but after bundling, it will display a warning | ||
| * containing a list of ids that have been wrapped which can be used as | ||
| * picomatch pattern for fine-tuning. | ||
| * @default "auto" | ||
| */ | ||
| strictRequires?: boolean | FilterPattern; | ||
| /** | ||
| * Sometimes you have to leave require statements unconverted. Pass an array | ||
| * containing the IDs or a `id => boolean` function. | ||
| * @default [] | ||
| */ | ||
| ignore?: ReadonlyArray<string> | ((id: string) => boolean); | ||
| /** | ||
| * In most cases, where `require` calls are inside a `try-catch` clause, | ||
| * they should be left unconverted as it requires an optional dependency | ||
| * that may or may not be installed beside the rolled up package. | ||
| * Due to the conversion of `require` to a static `import` - the call is | ||
| * hoisted to the top of the file, outside the `try-catch` clause. | ||
| * | ||
| * - `true`: Default. All `require` calls inside a `try` will be left unconverted. | ||
| * - `false`: All `require` calls inside a `try` will be converted as if the | ||
| * `try-catch` clause is not there. | ||
| * - `remove`: Remove all `require` calls from inside any `try` block. | ||
| * - `string[]`: Pass an array containing the IDs to left unconverted. | ||
| * - `((id: string) => boolean|'remove')`: Pass a function that controls | ||
| * individual IDs. | ||
| * | ||
| * @default true | ||
| */ | ||
| ignoreTryCatch?: boolean | 'remove' | ReadonlyArray<string> | ((id: string) => boolean | 'remove'); | ||
| /** | ||
| * Controls how to render imports from external dependencies. By default, | ||
| * this plugin assumes that all external dependencies are CommonJS. This | ||
| * means they are rendered as default imports to be compatible with e.g. | ||
| * NodeJS where ES modules can only import a default export from a CommonJS | ||
| * dependency. | ||
| * | ||
| * If you set `esmExternals` to `true`, this plugin assumes that all | ||
| * external dependencies are ES modules and respect the | ||
| * `requireReturnsDefault` option. If that option is not set, they will be | ||
| * rendered as namespace imports. | ||
| * | ||
| * You can also supply an array of ids to be treated as ES modules, or a | ||
| * function that will be passed each external id to determine whether it is | ||
| * an ES module. | ||
| * @default false | ||
| */ | ||
| esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean); | ||
| /** | ||
| * Controls what is returned when requiring an ES module from a CommonJS file. | ||
| * When using the `esmExternals` option, this will also apply to external | ||
| * modules. By default, this plugin will render those imports as namespace | ||
| * imports i.e. | ||
| * | ||
| * ```js | ||
| * // input | ||
| * const foo = require('foo'); | ||
| * | ||
| * // output | ||
| * import * as foo from 'foo'; | ||
| * ``` | ||
| * | ||
| * However, there are some situations where this may not be desired. | ||
| * For these situations, you can change Rollup's behaviour either globally or | ||
| * per module. To change it globally, set the `requireReturnsDefault` option | ||
| * to one of the following values: | ||
| * | ||
| * - `false`: This is the default, requiring an ES module returns its | ||
| * namespace. This is the only option that will also add a marker | ||
| * `__esModule: true` to the namespace to support interop patterns in | ||
| * CommonJS modules that are transpiled ES modules. | ||
| * - `"namespace"`: Like `false`, requiring an ES module returns its | ||
| * namespace, but the plugin does not add the `__esModule` marker and thus | ||
| * creates more efficient code. For external dependencies when using | ||
| * `esmExternals: true`, no additional interop code is generated. | ||
| * - `"auto"`: This is complementary to how `output.exports: "auto"` works in | ||
| * Rollup: If a module has a default export and no named exports, requiring | ||
| * that module returns the default export. In all other cases, the namespace | ||
| * is returned. For external dependencies when using `esmExternals: true`, a | ||
| * corresponding interop helper is added. | ||
| * - `"preferred"`: If a module has a default export, requiring that module | ||
| * always returns the default export, no matter whether additional named | ||
| * exports exist. This is similar to how previous versions of this plugin | ||
| * worked. Again for external dependencies when using `esmExternals: true`, | ||
| * an interop helper is added. | ||
| * - `true`: This will always try to return the default export on require | ||
| * without checking if it actually exists. This can throw at build time if | ||
| * there is no default export. This is how external dependencies are handled | ||
| * when `esmExternals` is not used. The advantage over the other options is | ||
| * that, like `false`, this does not add an interop helper for external | ||
| * dependencies, keeping the code lean. | ||
| * | ||
| * To change this for individual modules, you can supply a function for | ||
| * `requireReturnsDefault` instead. This function will then be called once for | ||
| * each required ES module or external dependency with the corresponding id | ||
| * and allows you to return different values for different modules. | ||
| * @default false | ||
| */ | ||
| requireReturnsDefault?: RequireReturnsDefaultOption | ((id: string) => RequireReturnsDefaultOption); | ||
| /** | ||
| * @default "auto" | ||
| */ | ||
| defaultIsModuleExports?: DefaultIsModuleExportsOption | ((id: string) => DefaultIsModuleExportsOption); | ||
| /** | ||
| * Some modules contain dynamic `require` calls, or require modules that | ||
| * contain circular dependencies, which are not handled well by static | ||
| * imports. Including those modules as `dynamicRequireTargets` will simulate a | ||
| * CommonJS (NodeJS-like) environment for them with support for dynamic | ||
| * dependencies. It also enables `strictRequires` for those modules. | ||
| * | ||
| * Note: In extreme cases, this feature may result in some paths being | ||
| * rendered as absolute in the final bundle. The plugin tries to avoid | ||
| * exposing paths from the local machine, but if you are `dynamicRequirePaths` | ||
| * with paths that are far away from your project's folder, that may require | ||
| * replacing strings like `"/Users/John/Desktop/foo-project/"` -> `"/"`. | ||
| */ | ||
| dynamicRequireTargets?: string | ReadonlyArray<string>; | ||
| /** | ||
| * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory | ||
| * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/` | ||
| * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your | ||
| * home directory name. By default, it uses the current working directory. | ||
| */ | ||
| dynamicRequireRoot?: string; | ||
| /** | ||
| * When enabled, external Node built-ins (e.g., `node:fs`) required from wrapped CommonJS modules | ||
| * will use `createRequire(import.meta.url)` instead of being hoisted as ESM imports. This prevents | ||
| * eager loading of Node built-ins at module initialization time. | ||
| * | ||
| * Note: This option adds a dependency on `node:module` in the output, which may not be available | ||
| * in some environments like edge runtimes (Cloudflare Workers, Vercel Edge Runtime). | ||
| * | ||
| * @default false | ||
| */ | ||
| requireNodeBuiltins?: boolean; | ||
| } | ||
| /** | ||
| * Convert CommonJS modules to ES6, so they can be included in a Rollup bundle | ||
| */ | ||
| declare function commonjs(options?: RollupCommonJSOptions): Plugin; | ||
| //#endregion | ||
| export { commonjs as t }; |
| import { i as __toESM, n as __exportAll, r as __require, t as __commonJSMin } from "../_common.mjs"; | ||
| import { $ as resolveModulePath, Y as readPackageJSON, at as join$1, ct as resolve$1, nt as dirname$1, ot as normalize$1, q as findWorkspaceDir, rt as extname$1, tt as basename$1 } from "../_build/common.mjs"; | ||
| import { existsSync, promises, readFileSync, statSync } from "node:fs"; | ||
| import { readFile, rm } from "node:fs/promises"; | ||
| import { pathToFileURL } from "node:url"; | ||
| import { homedir } from "node:os"; | ||
| import { resolve } from "node:path"; | ||
| import { createJiti } from "jiti"; | ||
| import destr from "destr"; | ||
| import { defu } from "defu"; | ||
| //#region node_modules/.pnpm/dotenv@17.2.3/node_modules/dotenv/package.json | ||
| var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => { | ||
| module.exports = { | ||
| "name": "dotenv", | ||
| "version": "17.2.3", | ||
| "description": "Loads environment variables from .env file", | ||
| "main": "lib/main.js", | ||
| "types": "lib/main.d.ts", | ||
| "exports": { | ||
| ".": { | ||
| "types": "./lib/main.d.ts", | ||
| "require": "./lib/main.js", | ||
| "default": "./lib/main.js" | ||
| }, | ||
| "./config": "./config.js", | ||
| "./config.js": "./config.js", | ||
| "./lib/env-options": "./lib/env-options.js", | ||
| "./lib/env-options.js": "./lib/env-options.js", | ||
| "./lib/cli-options": "./lib/cli-options.js", | ||
| "./lib/cli-options.js": "./lib/cli-options.js", | ||
| "./package.json": "./package.json" | ||
| }, | ||
| "scripts": { | ||
| "dts-check": "tsc --project tests/types/tsconfig.json", | ||
| "lint": "standard", | ||
| "pretest": "npm run lint && npm run dts-check", | ||
| "test": "tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000", | ||
| "test:coverage": "tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov", | ||
| "prerelease": "npm test", | ||
| "release": "standard-version" | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git://github.com/motdotla/dotenv.git" | ||
| }, | ||
| "homepage": "https://github.com/motdotla/dotenv#readme", | ||
| "funding": "https://dotenvx.com", | ||
| "keywords": [ | ||
| "dotenv", | ||
| "env", | ||
| ".env", | ||
| "environment", | ||
| "variables", | ||
| "config", | ||
| "settings" | ||
| ], | ||
| "readmeFilename": "README.md", | ||
| "license": "BSD-2-Clause", | ||
| "devDependencies": { | ||
| "@types/node": "^18.11.3", | ||
| "decache": "^4.6.2", | ||
| "sinon": "^14.0.1", | ||
| "standard": "^17.0.0", | ||
| "standard-version": "^9.5.0", | ||
| "tap": "^19.2.0", | ||
| "typescript": "^4.8.4" | ||
| }, | ||
| "engines": { "node": ">=12" }, | ||
| "browser": { "fs": false } | ||
| }; | ||
| })); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/dotenv@17.2.3/node_modules/dotenv/lib/main.js | ||
| var require_main = /* @__PURE__ */ __commonJSMin(((exports, module) => { | ||
| const fs$1 = __require("fs"); | ||
| const path$1 = __require("path"); | ||
| const os$1 = __require("os"); | ||
| const crypto = __require("crypto"); | ||
| const version = require_package().version; | ||
| const TIPS = [ | ||
| "🔐 encrypt with Dotenvx: https://dotenvx.com", | ||
| "🔐 prevent committing .env to code: https://dotenvx.com/precommit", | ||
| "🔐 prevent building .env in docker: https://dotenvx.com/prebuild", | ||
| "📡 add observability to secrets: https://dotenvx.com/ops", | ||
| "👥 sync secrets across teammates & machines: https://dotenvx.com/ops", | ||
| "🗂️ backup and recover secrets: https://dotenvx.com/ops", | ||
| "✅ audit secrets and track compliance: https://dotenvx.com/ops", | ||
| "🔄 add secrets lifecycle management: https://dotenvx.com/ops", | ||
| "🔑 add access controls to secrets: https://dotenvx.com/ops", | ||
| "🛠️ run anywhere with `dotenvx run -- yourcommand`", | ||
| "⚙️ specify custom .env file path with { path: '/custom/path/.env' }", | ||
| "⚙️ enable debug logging with { debug: true }", | ||
| "⚙️ override existing env vars with { override: true }", | ||
| "⚙️ suppress all logs with { quiet: true }", | ||
| "⚙️ write to custom object with { processEnv: myObject }", | ||
| "⚙️ load multiple .env files with { path: ['.env.local', '.env'] }" | ||
| ]; | ||
| function _getRandomTip() { | ||
| return TIPS[Math.floor(Math.random() * TIPS.length)]; | ||
| } | ||
| function parseBoolean(value) { | ||
| if (typeof value === "string") return ![ | ||
| "false", | ||
| "0", | ||
| "no", | ||
| "off", | ||
| "" | ||
| ].includes(value.toLowerCase()); | ||
| return Boolean(value); | ||
| } | ||
| function supportsAnsi() { | ||
| return process.stdout.isTTY; | ||
| } | ||
| function dim(text) { | ||
| return supportsAnsi() ? `\x1b[2m${text}\x1b[0m` : text; | ||
| } | ||
| const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm; | ||
| function parse(src) { | ||
| const obj = {}; | ||
| let lines = src.toString(); | ||
| lines = lines.replace(/\r\n?/gm, "\n"); | ||
| let match; | ||
| while ((match = LINE.exec(lines)) != null) { | ||
| const key = match[1]; | ||
| let value = match[2] || ""; | ||
| value = value.trim(); | ||
| const maybeQuote = value[0]; | ||
| value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2"); | ||
| if (maybeQuote === "\"") { | ||
| value = value.replace(/\\n/g, "\n"); | ||
| value = value.replace(/\\r/g, "\r"); | ||
| } | ||
| obj[key] = value; | ||
| } | ||
| return obj; | ||
| } | ||
| function _parseVault(options) { | ||
| options = options || {}; | ||
| const vaultPath = _vaultPath(options); | ||
| options.path = vaultPath; | ||
| const result = DotenvModule.configDotenv(options); | ||
| if (!result.parsed) { | ||
| const err = /* @__PURE__ */ new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`); | ||
| err.code = "MISSING_DATA"; | ||
| throw err; | ||
| } | ||
| const keys = _dotenvKey(options).split(","); | ||
| const length = keys.length; | ||
| let decrypted; | ||
| for (let i = 0; i < length; i++) try { | ||
| const attrs = _instructions(result, keys[i].trim()); | ||
| decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); | ||
| break; | ||
| } catch (error) { | ||
| if (i + 1 >= length) throw error; | ||
| } | ||
| return DotenvModule.parse(decrypted); | ||
| } | ||
| function _warn(message) { | ||
| console.error(`[dotenv@${version}][WARN] ${message}`); | ||
| } | ||
| function _debug(message) { | ||
| console.log(`[dotenv@${version}][DEBUG] ${message}`); | ||
| } | ||
| function _log(message) { | ||
| console.log(`[dotenv@${version}] ${message}`); | ||
| } | ||
| function _dotenvKey(options) { | ||
| if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) return options.DOTENV_KEY; | ||
| if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) return process.env.DOTENV_KEY; | ||
| return ""; | ||
| } | ||
| function _instructions(result, dotenvKey) { | ||
| let uri; | ||
| try { | ||
| uri = new URL(dotenvKey); | ||
| } catch (error) { | ||
| if (error.code === "ERR_INVALID_URL") { | ||
| const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development"); | ||
| err.code = "INVALID_DOTENV_KEY"; | ||
| throw err; | ||
| } | ||
| throw error; | ||
| } | ||
| const key = uri.password; | ||
| if (!key) { | ||
| const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing key part"); | ||
| err.code = "INVALID_DOTENV_KEY"; | ||
| throw err; | ||
| } | ||
| const environment = uri.searchParams.get("environment"); | ||
| if (!environment) { | ||
| const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing environment part"); | ||
| err.code = "INVALID_DOTENV_KEY"; | ||
| throw err; | ||
| } | ||
| const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; | ||
| const ciphertext = result.parsed[environmentKey]; | ||
| if (!ciphertext) { | ||
| const err = /* @__PURE__ */ new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`); | ||
| err.code = "NOT_FOUND_DOTENV_ENVIRONMENT"; | ||
| throw err; | ||
| } | ||
| return { | ||
| ciphertext, | ||
| key | ||
| }; | ||
| } | ||
| function _vaultPath(options) { | ||
| let possibleVaultPath = null; | ||
| if (options && options.path && options.path.length > 0) if (Array.isArray(options.path)) { | ||
| for (const filepath of options.path) if (fs$1.existsSync(filepath)) possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`; | ||
| } else possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`; | ||
| else possibleVaultPath = path$1.resolve(process.cwd(), ".env.vault"); | ||
| if (fs$1.existsSync(possibleVaultPath)) return possibleVaultPath; | ||
| return null; | ||
| } | ||
| function _resolveHome(envPath) { | ||
| return envPath[0] === "~" ? path$1.join(os$1.homedir(), envPath.slice(1)) : envPath; | ||
| } | ||
| function _configVault(options) { | ||
| const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options && options.debug); | ||
| const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || options && options.quiet); | ||
| if (debug || !quiet) _log("Loading env from encrypted .env.vault"); | ||
| const parsed = DotenvModule._parseVault(options); | ||
| let processEnv = process.env; | ||
| if (options && options.processEnv != null) processEnv = options.processEnv; | ||
| DotenvModule.populate(processEnv, parsed, options); | ||
| return { parsed }; | ||
| } | ||
| function configDotenv(options) { | ||
| const dotenvPath = path$1.resolve(process.cwd(), ".env"); | ||
| let encoding = "utf8"; | ||
| let processEnv = process.env; | ||
| if (options && options.processEnv != null) processEnv = options.processEnv; | ||
| let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || options && options.debug); | ||
| let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || options && options.quiet); | ||
| if (options && options.encoding) encoding = options.encoding; | ||
| else if (debug) _debug("No encoding is specified. UTF-8 is used by default"); | ||
| let optionPaths = [dotenvPath]; | ||
| if (options && options.path) if (!Array.isArray(options.path)) optionPaths = [_resolveHome(options.path)]; | ||
| else { | ||
| optionPaths = []; | ||
| for (const filepath of options.path) optionPaths.push(_resolveHome(filepath)); | ||
| } | ||
| let lastError; | ||
| const parsedAll = {}; | ||
| for (const path$2 of optionPaths) try { | ||
| const parsed = DotenvModule.parse(fs$1.readFileSync(path$2, { encoding })); | ||
| DotenvModule.populate(parsedAll, parsed, options); | ||
| } catch (e) { | ||
| if (debug) _debug(`Failed to load ${path$2} ${e.message}`); | ||
| lastError = e; | ||
| } | ||
| const populated = DotenvModule.populate(processEnv, parsedAll, options); | ||
| debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug); | ||
| quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet); | ||
| if (debug || !quiet) { | ||
| const keysCount = Object.keys(populated).length; | ||
| const shortPaths = []; | ||
| for (const filePath of optionPaths) try { | ||
| const relative$1 = path$1.relative(process.cwd(), filePath); | ||
| shortPaths.push(relative$1); | ||
| } catch (e) { | ||
| if (debug) _debug(`Failed to load ${filePath} ${e.message}`); | ||
| lastError = e; | ||
| } | ||
| _log(`injecting env (${keysCount}) from ${shortPaths.join(",")} ${dim(`-- tip: ${_getRandomTip()}`)}`); | ||
| } | ||
| if (lastError) return { | ||
| parsed: parsedAll, | ||
| error: lastError | ||
| }; | ||
| else return { parsed: parsedAll }; | ||
| } | ||
| function config(options) { | ||
| if (_dotenvKey(options).length === 0) return DotenvModule.configDotenv(options); | ||
| const vaultPath = _vaultPath(options); | ||
| if (!vaultPath) { | ||
| _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`); | ||
| return DotenvModule.configDotenv(options); | ||
| } | ||
| return DotenvModule._configVault(options); | ||
| } | ||
| function decrypt(encrypted, keyStr) { | ||
| const key = Buffer.from(keyStr.slice(-64), "hex"); | ||
| let ciphertext = Buffer.from(encrypted, "base64"); | ||
| const nonce = ciphertext.subarray(0, 12); | ||
| const authTag = ciphertext.subarray(-16); | ||
| ciphertext = ciphertext.subarray(12, -16); | ||
| try { | ||
| const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce); | ||
| aesgcm.setAuthTag(authTag); | ||
| return `${aesgcm.update(ciphertext)}${aesgcm.final()}`; | ||
| } catch (error) { | ||
| const isRange = error instanceof RangeError; | ||
| const invalidKeyLength = error.message === "Invalid key length"; | ||
| const decryptionFailed = error.message === "Unsupported state or unable to authenticate data"; | ||
| if (isRange || invalidKeyLength) { | ||
| const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)"); | ||
| err.code = "INVALID_DOTENV_KEY"; | ||
| throw err; | ||
| } else if (decryptionFailed) { | ||
| const err = /* @__PURE__ */ new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY"); | ||
| err.code = "DECRYPTION_FAILED"; | ||
| throw err; | ||
| } else throw error; | ||
| } | ||
| } | ||
| function populate(processEnv, parsed, options = {}) { | ||
| const debug = Boolean(options && options.debug); | ||
| const override = Boolean(options && options.override); | ||
| const populated = {}; | ||
| if (typeof parsed !== "object") { | ||
| const err = /* @__PURE__ */ new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate"); | ||
| err.code = "OBJECT_REQUIRED"; | ||
| throw err; | ||
| } | ||
| for (const key of Object.keys(parsed)) if (Object.prototype.hasOwnProperty.call(processEnv, key)) { | ||
| if (override === true) { | ||
| processEnv[key] = parsed[key]; | ||
| populated[key] = parsed[key]; | ||
| } | ||
| if (debug) if (override === true) _debug(`"${key}" is already defined and WAS overwritten`); | ||
| else _debug(`"${key}" is already defined and was NOT overwritten`); | ||
| } else { | ||
| processEnv[key] = parsed[key]; | ||
| populated[key] = parsed[key]; | ||
| } | ||
| return populated; | ||
| } | ||
| const DotenvModule = { | ||
| configDotenv, | ||
| _configVault, | ||
| _parseVault, | ||
| config, | ||
| decrypt, | ||
| parse, | ||
| populate | ||
| }; | ||
| module.exports.configDotenv = DotenvModule.configDotenv; | ||
| module.exports._configVault = DotenvModule._configVault; | ||
| module.exports._parseVault = DotenvModule._parseVault; | ||
| module.exports.config = DotenvModule.config; | ||
| module.exports.decrypt = DotenvModule.decrypt; | ||
| module.exports.parse = DotenvModule.parse; | ||
| module.exports.populate = DotenvModule.populate; | ||
| module.exports = DotenvModule; | ||
| })); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/rc9@2.1.2/node_modules/rc9/dist/index.mjs | ||
| function isBuffer(obj) { | ||
| return obj && obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj); | ||
| } | ||
| function keyIdentity(key) { | ||
| return key; | ||
| } | ||
| function flatten(target, opts) { | ||
| opts = opts || {}; | ||
| const delimiter$1 = opts.delimiter || "."; | ||
| const maxDepth = opts.maxDepth; | ||
| const transformKey = opts.transformKey || keyIdentity; | ||
| const output = {}; | ||
| function step(object, prev, currentDepth) { | ||
| currentDepth = currentDepth || 1; | ||
| Object.keys(object).forEach(function(key) { | ||
| const value = object[key]; | ||
| const isarray = opts.safe && Array.isArray(value); | ||
| const type$1 = Object.prototype.toString.call(value); | ||
| const isbuffer = isBuffer(value); | ||
| const isobject = type$1 === "[object Object]" || type$1 === "[object Array]"; | ||
| const newKey = prev ? prev + delimiter$1 + transformKey(key) : transformKey(key); | ||
| if (!isarray && !isbuffer && isobject && Object.keys(value).length && (!opts.maxDepth || currentDepth < maxDepth)) return step(value, newKey, currentDepth + 1); | ||
| output[newKey] = value; | ||
| }); | ||
| } | ||
| step(target); | ||
| return output; | ||
| } | ||
| function unflatten(target, opts) { | ||
| opts = opts || {}; | ||
| const delimiter$1 = opts.delimiter || "."; | ||
| const overwrite = opts.overwrite || false; | ||
| const transformKey = opts.transformKey || keyIdentity; | ||
| const result = {}; | ||
| if (isBuffer(target) || Object.prototype.toString.call(target) !== "[object Object]") return target; | ||
| function getkey(key) { | ||
| const parsedKey = Number(key); | ||
| return isNaN(parsedKey) || key.indexOf(".") !== -1 || opts.object ? key : parsedKey; | ||
| } | ||
| function addKeys(keyPrefix, recipient, target$1) { | ||
| return Object.keys(target$1).reduce(function(result$1, key) { | ||
| result$1[keyPrefix + delimiter$1 + key] = target$1[key]; | ||
| return result$1; | ||
| }, recipient); | ||
| } | ||
| function isEmpty(val) { | ||
| const type$1 = Object.prototype.toString.call(val); | ||
| const isArray = type$1 === "[object Array]"; | ||
| const isObject = type$1 === "[object Object]"; | ||
| if (!val) return true; | ||
| else if (isArray) return !val.length; | ||
| else if (isObject) return !Object.keys(val).length; | ||
| } | ||
| target = Object.keys(target).reduce(function(result$1, key) { | ||
| const type$1 = Object.prototype.toString.call(target[key]); | ||
| if (!(type$1 === "[object Object]" || type$1 === "[object Array]") || isEmpty(target[key])) { | ||
| result$1[key] = target[key]; | ||
| return result$1; | ||
| } else return addKeys(key, result$1, flatten(target[key], opts)); | ||
| }, {}); | ||
| Object.keys(target).forEach(function(key) { | ||
| const split = key.split(delimiter$1).map(transformKey); | ||
| let key1 = getkey(split.shift()); | ||
| let key2 = getkey(split[0]); | ||
| let recipient = result; | ||
| while (key2 !== void 0) { | ||
| if (key1 === "__proto__") return; | ||
| const type$1 = Object.prototype.toString.call(recipient[key1]); | ||
| const isobject = type$1 === "[object Object]" || type$1 === "[object Array]"; | ||
| if (!overwrite && !isobject && typeof recipient[key1] !== "undefined") return; | ||
| if (overwrite && !isobject || !overwrite && recipient[key1] == null) recipient[key1] = typeof key2 === "number" && !opts.object ? [] : {}; | ||
| recipient = recipient[key1]; | ||
| if (split.length > 0) { | ||
| key1 = getkey(split.shift()); | ||
| key2 = getkey(split[0]); | ||
| } | ||
| } | ||
| recipient[key1] = unflatten(target[key], opts); | ||
| }); | ||
| return result; | ||
| } | ||
| const RE_KEY_VAL = /^\s*([^\s=]+)\s*=\s*(.*)?\s*$/; | ||
| const RE_LINES = /\n|\r|\r\n/; | ||
| const defaults = { | ||
| name: ".conf", | ||
| dir: process.cwd(), | ||
| flat: false | ||
| }; | ||
| function withDefaults(options) { | ||
| if (typeof options === "string") options = { name: options }; | ||
| return { | ||
| ...defaults, | ||
| ...options | ||
| }; | ||
| } | ||
| function parse(contents, options = {}) { | ||
| const config = {}; | ||
| const lines = contents.split(RE_LINES); | ||
| for (const line of lines) { | ||
| const match = line.match(RE_KEY_VAL); | ||
| if (!match) continue; | ||
| const key = match[1]; | ||
| if (!key || key === "__proto__" || key === "constructor") continue; | ||
| const value = destr((match[2] || "").trim()); | ||
| if (key.endsWith("[]")) { | ||
| const nkey = key.slice(0, Math.max(0, key.length - 2)); | ||
| config[nkey] = (config[nkey] || []).concat(value); | ||
| continue; | ||
| } | ||
| config[key] = value; | ||
| } | ||
| return options.flat ? config : unflatten(config, { overwrite: true }); | ||
| } | ||
| function parseFile(path$2, options) { | ||
| if (!existsSync(path$2)) return {}; | ||
| return parse(readFileSync(path$2, "utf8"), options); | ||
| } | ||
| function read(options) { | ||
| options = withDefaults(options); | ||
| return parseFile(resolve(options.dir, options.name), options); | ||
| } | ||
| function readUser(options) { | ||
| options = withDefaults(options); | ||
| options.dir = process.env.XDG_CONFIG_HOME || homedir(); | ||
| return read(options); | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/perfect-debounce@2.0.0/node_modules/perfect-debounce/dist/index.mjs | ||
| const DEBOUNCE_DEFAULTS = { trailing: true }; | ||
| /** | ||
| Debounce functions | ||
| @param fn - Promise-returning/async function to debounce. | ||
| @param wait - Milliseconds to wait before calling `fn`. Default value is 25ms | ||
| @returns A function that delays calling `fn` until after `wait` milliseconds have elapsed since the last time it was called. | ||
| @example | ||
| ``` | ||
| import { debounce } from 'perfect-debounce'; | ||
| const expensiveCall = async input => input; | ||
| const debouncedFn = debounce(expensiveCall, 200); | ||
| for (const number of [1, 2, 3]) { | ||
| console.log(await debouncedFn(number)); | ||
| } | ||
| //=> 1 | ||
| //=> 2 | ||
| //=> 3 | ||
| ``` | ||
| */ | ||
| function debounce(fn, wait = 25, options = {}) { | ||
| options = { | ||
| ...DEBOUNCE_DEFAULTS, | ||
| ...options | ||
| }; | ||
| if (!Number.isFinite(wait)) throw new TypeError("Expected `wait` to be a finite number"); | ||
| let leadingValue; | ||
| let timeout; | ||
| let resolveList = []; | ||
| let currentPromise; | ||
| let trailingArgs; | ||
| const applyFn = (_this, args) => { | ||
| currentPromise = _applyPromised(fn, _this, args); | ||
| currentPromise.finally(() => { | ||
| currentPromise = null; | ||
| if (options.trailing && trailingArgs && !timeout) { | ||
| const promise = applyFn(_this, trailingArgs); | ||
| trailingArgs = null; | ||
| return promise; | ||
| } | ||
| }); | ||
| return currentPromise; | ||
| }; | ||
| const debounced = function(...args) { | ||
| if (options.trailing) trailingArgs = args; | ||
| if (currentPromise) return currentPromise; | ||
| return new Promise((resolve$2) => { | ||
| const shouldCallNow = !timeout && options.leading; | ||
| clearTimeout(timeout); | ||
| timeout = setTimeout(() => { | ||
| timeout = null; | ||
| const promise = options.leading ? leadingValue : applyFn(this, args); | ||
| trailingArgs = null; | ||
| for (const _resolve of resolveList) _resolve(promise); | ||
| resolveList = []; | ||
| }, wait); | ||
| if (shouldCallNow) { | ||
| leadingValue = applyFn(this, args); | ||
| resolve$2(leadingValue); | ||
| } else resolveList.push(resolve$2); | ||
| }); | ||
| }; | ||
| const _clearTimeout = (timer) => { | ||
| if (timer) { | ||
| clearTimeout(timer); | ||
| timeout = null; | ||
| } | ||
| }; | ||
| debounced.isPending = () => !!timeout; | ||
| debounced.cancel = () => { | ||
| _clearTimeout(timeout); | ||
| resolveList = []; | ||
| trailingArgs = null; | ||
| }; | ||
| debounced.flush = () => { | ||
| _clearTimeout(timeout); | ||
| if (!trailingArgs || currentPromise) return; | ||
| const args = trailingArgs; | ||
| trailingArgs = null; | ||
| return applyFn(this, args); | ||
| }; | ||
| return debounced; | ||
| } | ||
| async function _applyPromised(fn, _this, args) { | ||
| return await fn.apply(_this, args); | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/c12@3.3.3_magicast@0.5.1/node_modules/c12/dist/index.mjs | ||
| var dist_exports = /* @__PURE__ */ __exportAll({ | ||
| SUPPORTED_EXTENSIONS: () => SUPPORTED_EXTENSIONS, | ||
| loadConfig: () => loadConfig, | ||
| loadDotenv: () => loadDotenv, | ||
| setupDotenv: () => setupDotenv, | ||
| watchConfig: () => watchConfig | ||
| }); | ||
| var import_main = /* @__PURE__ */ __toESM(require_main(), 1); | ||
| /** | ||
| * Load and interpolate environment variables into `process.env`. | ||
| * If you need more control (or access to the values), consider using `loadDotenv` instead | ||
| * | ||
| */ | ||
| async function setupDotenv(options) { | ||
| const targetEnvironment = options.env ?? process.env; | ||
| const environment = await loadDotenv({ | ||
| cwd: options.cwd, | ||
| fileName: options.fileName ?? ".env", | ||
| env: targetEnvironment, | ||
| interpolate: options.interpolate ?? true | ||
| }); | ||
| const dotenvVars = getDotEnvVars(targetEnvironment); | ||
| for (const key in environment) { | ||
| if (key.startsWith("_")) continue; | ||
| if (targetEnvironment[key] === void 0 || dotenvVars.has(key)) targetEnvironment[key] = environment[key]; | ||
| } | ||
| return environment; | ||
| } | ||
| /** Load environment variables into an object. */ | ||
| async function loadDotenv(options) { | ||
| const environment = Object.create(null); | ||
| const cwd = resolve$1(options.cwd || "."); | ||
| const _fileName = options.fileName || ".env"; | ||
| const dotenvFiles = typeof _fileName === "string" ? [_fileName] : _fileName; | ||
| const dotenvVars = getDotEnvVars(options.env || {}); | ||
| Object.assign(environment, options.env); | ||
| for (const file of dotenvFiles) { | ||
| const dotenvFile = resolve$1(cwd, file); | ||
| if (!statSync(dotenvFile, { throwIfNoEntry: false })?.isFile()) continue; | ||
| const parsed = import_main.parse(await promises.readFile(dotenvFile, "utf8")); | ||
| for (const key in parsed) { | ||
| if (key in environment && !dotenvVars.has(key)) continue; | ||
| environment[key] = parsed[key]; | ||
| dotenvVars.add(key); | ||
| } | ||
| } | ||
| if (options.interpolate) interpolate(environment); | ||
| return environment; | ||
| } | ||
| function interpolate(target, source = {}, parse$1 = (v) => v) { | ||
| function getValue(key) { | ||
| return source[key] === void 0 ? target[key] : source[key]; | ||
| } | ||
| function interpolate$1(value, parents = []) { | ||
| if (typeof value !== "string") return value; | ||
| return parse$1((value.match(/(.?\${?(?:[\w:]+)?}?)/g) || []).reduce((newValue, match) => { | ||
| const parts = /(.?)\${?([\w:]+)?}?/g.exec(match) || []; | ||
| const prefix = parts[1]; | ||
| let value$1, replacePart; | ||
| if (prefix === "\\") { | ||
| replacePart = parts[0] || ""; | ||
| value$1 = replacePart.replace(String.raw`\$`, "$"); | ||
| } else { | ||
| const key = parts[2]; | ||
| replacePart = (parts[0] || "").slice(prefix.length); | ||
| if (parents.includes(key)) { | ||
| console.warn(`Please avoid recursive environment variables ( loop: ${parents.join(" > ")} > ${key} )`); | ||
| return ""; | ||
| } | ||
| value$1 = getValue(key); | ||
| value$1 = interpolate$1(value$1, [...parents, key]); | ||
| } | ||
| return value$1 === void 0 ? newValue : newValue.replace(replacePart, value$1); | ||
| }, value)); | ||
| } | ||
| for (const key in target) target[key] = interpolate$1(getValue(key)); | ||
| } | ||
| function getDotEnvVars(targetEnvironment) { | ||
| const globalRegistry = globalThis.__c12_dotenv_vars__ ||= /* @__PURE__ */ new Map(); | ||
| if (!globalRegistry.has(targetEnvironment)) globalRegistry.set(targetEnvironment, /* @__PURE__ */ new Set()); | ||
| return globalRegistry.get(targetEnvironment); | ||
| } | ||
| const _normalize = (p) => p?.replace(/\\/g, "/"); | ||
| const ASYNC_LOADERS = { | ||
| ".yaml": () => import("./confbox.mjs").then((n) => n.a).then((r) => r.parseYAML), | ||
| ".yml": () => import("./confbox.mjs").then((n) => n.a).then((r) => r.parseYAML), | ||
| ".jsonc": () => import("./confbox.mjs").then((n) => n.t).then((r) => r.parseJSONC), | ||
| ".json5": () => import("./confbox.mjs").then((n) => n.o).then((r) => r.parseJSON5), | ||
| ".toml": () => import("./confbox.mjs").then((n) => n.r).then((r) => r.parseTOML) | ||
| }; | ||
| const SUPPORTED_EXTENSIONS = Object.freeze([ | ||
| ".js", | ||
| ".ts", | ||
| ".mjs", | ||
| ".cjs", | ||
| ".mts", | ||
| ".cts", | ||
| ".json", | ||
| ".jsonc", | ||
| ".json5", | ||
| ".yaml", | ||
| ".yml", | ||
| ".toml" | ||
| ]); | ||
| async function loadConfig(options) { | ||
| options.cwd = resolve$1(process.cwd(), options.cwd || "."); | ||
| options.name = options.name || "config"; | ||
| options.envName = options.envName ?? process.env.NODE_ENV; | ||
| options.configFile = options.configFile ?? (options.name === "config" ? "config" : `${options.name}.config`); | ||
| options.rcFile = options.rcFile ?? `.${options.name}rc`; | ||
| if (options.extend !== false) options.extend = { | ||
| extendKey: "extends", | ||
| ...options.extend | ||
| }; | ||
| const _merger = options.merger || defu; | ||
| options.jiti = options.jiti || createJiti(join$1(options.cwd, options.configFile), { | ||
| interopDefault: true, | ||
| moduleCache: false, | ||
| extensions: [...SUPPORTED_EXTENSIONS], | ||
| ...options.jitiOptions | ||
| }); | ||
| const r = { | ||
| config: {}, | ||
| cwd: options.cwd, | ||
| configFile: resolve$1(options.cwd, options.configFile), | ||
| layers: [], | ||
| _configFile: void 0 | ||
| }; | ||
| const rawConfigs = { | ||
| overrides: options.overrides, | ||
| main: void 0, | ||
| rc: void 0, | ||
| packageJson: void 0, | ||
| defaultConfig: options.defaultConfig | ||
| }; | ||
| if (options.dotenv) await setupDotenv({ | ||
| cwd: options.cwd, | ||
| ...options.dotenv === true ? {} : options.dotenv | ||
| }); | ||
| const _mainConfig = await resolveConfig(".", options); | ||
| if (_mainConfig.configFile) { | ||
| rawConfigs.main = _mainConfig.config; | ||
| r.configFile = _mainConfig.configFile; | ||
| r._configFile = _mainConfig._configFile; | ||
| } | ||
| if (_mainConfig.meta) r.meta = _mainConfig.meta; | ||
| if (options.rcFile) { | ||
| const rcSources = []; | ||
| rcSources.push(read({ | ||
| name: options.rcFile, | ||
| dir: options.cwd | ||
| })); | ||
| if (options.globalRc) { | ||
| const workspaceDir = await findWorkspaceDir(options.cwd).catch(() => {}); | ||
| if (workspaceDir) rcSources.push(read({ | ||
| name: options.rcFile, | ||
| dir: workspaceDir | ||
| })); | ||
| rcSources.push(readUser({ | ||
| name: options.rcFile, | ||
| dir: options.cwd | ||
| })); | ||
| } | ||
| rawConfigs.rc = _merger({}, ...rcSources); | ||
| } | ||
| if (options.packageJson) { | ||
| const keys = (Array.isArray(options.packageJson) ? options.packageJson : [typeof options.packageJson === "string" ? options.packageJson : options.name]).filter((t) => t && typeof t === "string"); | ||
| const pkgJsonFile = await readPackageJSON(options.cwd).catch(() => {}); | ||
| rawConfigs.packageJson = _merger({}, ...keys.map((key) => pkgJsonFile?.[key])); | ||
| } | ||
| const configs = {}; | ||
| for (const key in rawConfigs) { | ||
| const value = rawConfigs[key]; | ||
| configs[key] = await (typeof value === "function" ? value({ | ||
| configs, | ||
| rawConfigs | ||
| }) : value); | ||
| } | ||
| if (Array.isArray(configs.main)) r.config = configs.main; | ||
| else { | ||
| r.config = _merger(configs.overrides, configs.main, configs.rc, configs.packageJson, configs.defaultConfig); | ||
| if (options.extend) { | ||
| await extendConfig(r.config, options); | ||
| r.layers = r.config._layers; | ||
| delete r.config._layers; | ||
| r.config = _merger(r.config, ...r.layers.map((e) => e.config)); | ||
| } | ||
| } | ||
| r.layers = [...[ | ||
| configs.overrides && { | ||
| config: configs.overrides, | ||
| configFile: void 0, | ||
| cwd: void 0 | ||
| }, | ||
| { | ||
| config: configs.main, | ||
| configFile: options.configFile, | ||
| cwd: options.cwd | ||
| }, | ||
| configs.rc && { | ||
| config: configs.rc, | ||
| configFile: options.rcFile | ||
| }, | ||
| configs.packageJson && { | ||
| config: configs.packageJson, | ||
| configFile: "package.json" | ||
| } | ||
| ].filter((l) => l && l.config), ...r.layers]; | ||
| if (options.defaults) r.config = _merger(r.config, options.defaults); | ||
| if (options.omit$Keys) { | ||
| for (const key in r.config) if (key.startsWith("$")) delete r.config[key]; | ||
| } | ||
| if (options.configFileRequired && !r._configFile) throw new Error(`Required config (${r.configFile}) cannot be resolved.`); | ||
| return r; | ||
| } | ||
| async function extendConfig(config, options) { | ||
| config._layers = config._layers || []; | ||
| if (!options.extend) return; | ||
| let keys = options.extend.extendKey; | ||
| if (typeof keys === "string") keys = [keys]; | ||
| const extendSources = []; | ||
| for (const key of keys) { | ||
| extendSources.push(...(Array.isArray(config[key]) ? config[key] : [config[key]]).filter(Boolean)); | ||
| delete config[key]; | ||
| } | ||
| for (let extendSource of extendSources) { | ||
| const originalExtendSource = extendSource; | ||
| let sourceOptions = {}; | ||
| if (extendSource.source) { | ||
| sourceOptions = extendSource.options || {}; | ||
| extendSource = extendSource.source; | ||
| } | ||
| if (Array.isArray(extendSource)) { | ||
| sourceOptions = extendSource[1] || {}; | ||
| extendSource = extendSource[0]; | ||
| } | ||
| if (typeof extendSource !== "string") { | ||
| console.warn(`Cannot extend config from \`${JSON.stringify(originalExtendSource)}\` in ${options.cwd}`); | ||
| continue; | ||
| } | ||
| const _config = await resolveConfig(extendSource, options, sourceOptions); | ||
| if (!_config.config) { | ||
| console.warn(`Cannot extend config from \`${extendSource}\` in ${options.cwd}`); | ||
| continue; | ||
| } | ||
| await extendConfig(_config.config, { | ||
| ...options, | ||
| cwd: _config.cwd | ||
| }); | ||
| config._layers.push(_config); | ||
| if (_config.config._layers) { | ||
| config._layers.push(..._config.config._layers); | ||
| delete _config.config._layers; | ||
| } | ||
| } | ||
| } | ||
| const GIGET_PREFIXES = [ | ||
| "gh:", | ||
| "github:", | ||
| "gitlab:", | ||
| "bitbucket:", | ||
| "https://", | ||
| "http://" | ||
| ]; | ||
| const NPM_PACKAGE_RE = /^(@[\da-z~-][\d._a-z~-]*\/)?[\da-z~-][\d._a-z~-]*($|\/.*)/; | ||
| async function resolveConfig(source, options, sourceOptions = {}) { | ||
| if (options.resolve) { | ||
| const res$1 = await options.resolve(source, options); | ||
| if (res$1) return res$1; | ||
| } | ||
| const _merger = options.merger || defu; | ||
| const customProviderKeys = Object.keys(sourceOptions.giget?.providers || {}).map((key) => `${key}:`); | ||
| const gigetPrefixes = customProviderKeys.length > 0 ? [...new Set([...customProviderKeys, ...GIGET_PREFIXES])] : GIGET_PREFIXES; | ||
| if (options.giget !== false && gigetPrefixes.some((prefix) => source.startsWith(prefix))) { | ||
| const { downloadTemplate } = await import("./nypm+giget+tinyexec.mjs").then((n) => n.t); | ||
| const { digest } = await import("ohash"); | ||
| const cloneName = source.replace(/\W+/g, "_").split("_").splice(0, 3).join("_") + "_" + digest(source).slice(0, 10).replace(/[-_]/g, ""); | ||
| let cloneDir; | ||
| const localNodeModules = resolve$1(options.cwd, "node_modules"); | ||
| const parentDir = dirname$1(options.cwd); | ||
| if (basename$1(parentDir) === ".c12") cloneDir = join$1(parentDir, cloneName); | ||
| else if (existsSync(localNodeModules)) cloneDir = join$1(localNodeModules, ".c12", cloneName); | ||
| else cloneDir = process.env.XDG_CACHE_HOME ? resolve$1(process.env.XDG_CACHE_HOME, "c12", cloneName) : resolve$1(homedir(), ".cache/c12", cloneName); | ||
| if (existsSync(cloneDir) && !sourceOptions.install) await rm(cloneDir, { recursive: true }); | ||
| source = (await downloadTemplate(source, { | ||
| dir: cloneDir, | ||
| install: sourceOptions.install, | ||
| force: sourceOptions.install, | ||
| auth: sourceOptions.auth, | ||
| ...options.giget, | ||
| ...sourceOptions.giget | ||
| })).dir; | ||
| } | ||
| if (NPM_PACKAGE_RE.test(source)) source = tryResolve(source, options) || source; | ||
| const ext = extname$1(source); | ||
| const isDir = !ext || ext === basename$1(source); | ||
| const cwd = resolve$1(options.cwd, isDir ? source : dirname$1(source)); | ||
| if (isDir) source = options.configFile; | ||
| const res = { | ||
| config: void 0, | ||
| configFile: void 0, | ||
| cwd, | ||
| source, | ||
| sourceOptions | ||
| }; | ||
| res.configFile = tryResolve(resolve$1(cwd, source), options) || tryResolve(resolve$1(cwd, ".config", source.replace(/\.config$/, "")), options) || tryResolve(resolve$1(cwd, ".config", source), options) || source; | ||
| if (!existsSync(res.configFile)) return res; | ||
| res._configFile = res.configFile; | ||
| const configFileExt = extname$1(res.configFile) || ""; | ||
| if (configFileExt in ASYNC_LOADERS) res.config = (await ASYNC_LOADERS[configFileExt]())(await readFile(res.configFile, "utf8")); | ||
| else res.config = await options.jiti.import(res.configFile, { default: true }); | ||
| if (typeof res.config === "function") res.config = await res.config(options.context); | ||
| if (options.envName) { | ||
| const envConfig = { | ||
| ...res.config["$" + options.envName], | ||
| ...res.config.$env?.[options.envName] | ||
| }; | ||
| if (Object.keys(envConfig).length > 0) res.config = _merger(envConfig, res.config); | ||
| } | ||
| res.meta = defu(res.sourceOptions.meta, res.config.$meta); | ||
| delete res.config.$meta; | ||
| if (res.sourceOptions.overrides) res.config = _merger(res.sourceOptions.overrides, res.config); | ||
| res.configFile = _normalize(res.configFile); | ||
| res.source = _normalize(res.source); | ||
| return res; | ||
| } | ||
| function tryResolve(id, options) { | ||
| const res = resolveModulePath(id, { | ||
| try: true, | ||
| from: pathToFileURL(join$1(options.cwd || ".", options.configFile || "/")), | ||
| suffixes: ["", "/index"], | ||
| extensions: SUPPORTED_EXTENSIONS, | ||
| cache: false | ||
| }); | ||
| return res ? normalize$1(res) : void 0; | ||
| } | ||
| const eventMap = { | ||
| add: "created", | ||
| change: "updated", | ||
| unlink: "removed" | ||
| }; | ||
| async function watchConfig(options) { | ||
| let config = await loadConfig(options); | ||
| const configName = options.name || "config"; | ||
| const configFileName = options.configFile ?? (options.name === "config" ? "config" : `${options.name}.config`); | ||
| const watchingFiles = [...new Set((config.layers || []).filter((l) => l.cwd).flatMap((l) => [ | ||
| ...SUPPORTED_EXTENSIONS.flatMap((ext) => [ | ||
| resolve$1(l.cwd, configFileName + ext), | ||
| resolve$1(l.cwd, ".config", configFileName + ext), | ||
| resolve$1(l.cwd, ".config", configFileName.replace(/\.config$/, "") + ext) | ||
| ]), | ||
| l.source && resolve$1(l.cwd, l.source), | ||
| options.rcFile && resolve$1(l.cwd, typeof options.rcFile === "string" ? options.rcFile : `.${configName}rc`), | ||
| options.packageJson && resolve$1(l.cwd, "package.json") | ||
| ]).filter(Boolean))]; | ||
| const watch$1 = await import("./readdirp+chokidar.mjs").then((n) => n.t).then((r) => r.watch || r.default || r); | ||
| const { diff } = await import("ohash/utils"); | ||
| const _fswatcher = watch$1(watchingFiles, { | ||
| ignoreInitial: true, | ||
| ...options.chokidarOptions | ||
| }); | ||
| const onChange = async (event, path$2) => { | ||
| const type$1 = eventMap[event]; | ||
| if (!type$1) return; | ||
| if (options.onWatch) await options.onWatch({ | ||
| type: type$1, | ||
| path: path$2 | ||
| }); | ||
| const oldConfig = config; | ||
| try { | ||
| config = await loadConfig(options); | ||
| } catch (error) { | ||
| console.warn(`Failed to load config ${path$2}\n${error}`); | ||
| return; | ||
| } | ||
| const changeCtx = { | ||
| newConfig: config, | ||
| oldConfig, | ||
| getDiff: () => diff(oldConfig.config, config.config) | ||
| }; | ||
| if (options.acceptHMR) { | ||
| if (await options.acceptHMR(changeCtx)) return; | ||
| } | ||
| if (options.onUpdate) await options.onUpdate(changeCtx); | ||
| }; | ||
| if (options.debounce === false) _fswatcher.on("all", onChange); | ||
| else _fswatcher.on("all", debounce(onChange, options.debounce ?? 100)); | ||
| const utils = { | ||
| watchingFiles, | ||
| unwatch: async () => { | ||
| await _fswatcher.close(); | ||
| } | ||
| }; | ||
| return new Proxy(utils, { get(_, prop) { | ||
| if (prop in utils) return utils[prop]; | ||
| return config[prop]; | ||
| } }); | ||
| } | ||
| //#endregion | ||
| export { debounce as i, loadConfig as n, watchConfig as r, dist_exports as t }; |
| import { n as __exportAll } from "../_common.mjs"; | ||
| import { Stats, stat, unwatchFile, watch, watchFile } from "node:fs"; | ||
| import { lstat, open, readdir, realpath, stat as stat$1 } from "node:fs/promises"; | ||
| import { type } from "node:os"; | ||
| import * as sp from "node:path"; | ||
| import { join, relative, resolve, sep } from "node:path"; | ||
| import { EventEmitter } from "node:events"; | ||
| import { Readable } from "node:stream"; | ||
| //#region node_modules/.pnpm/readdirp@5.0.0/node_modules/readdirp/index.js | ||
| const EntryTypes = { | ||
| FILE_TYPE: "files", | ||
| DIR_TYPE: "directories", | ||
| FILE_DIR_TYPE: "files_directories", | ||
| EVERYTHING_TYPE: "all" | ||
| }; | ||
| const defaultOptions = { | ||
| root: ".", | ||
| fileFilter: (_entryInfo) => true, | ||
| directoryFilter: (_entryInfo) => true, | ||
| type: EntryTypes.FILE_TYPE, | ||
| lstat: false, | ||
| depth: 2147483648, | ||
| alwaysStat: false, | ||
| highWaterMark: 4096 | ||
| }; | ||
| Object.freeze(defaultOptions); | ||
| const RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR"; | ||
| const NORMAL_FLOW_ERRORS = new Set([ | ||
| "ENOENT", | ||
| "EPERM", | ||
| "EACCES", | ||
| "ELOOP", | ||
| RECURSIVE_ERROR_CODE | ||
| ]); | ||
| const ALL_TYPES = [ | ||
| EntryTypes.DIR_TYPE, | ||
| EntryTypes.EVERYTHING_TYPE, | ||
| EntryTypes.FILE_DIR_TYPE, | ||
| EntryTypes.FILE_TYPE | ||
| ]; | ||
| const DIR_TYPES = new Set([ | ||
| EntryTypes.DIR_TYPE, | ||
| EntryTypes.EVERYTHING_TYPE, | ||
| EntryTypes.FILE_DIR_TYPE | ||
| ]); | ||
| const FILE_TYPES = new Set([ | ||
| EntryTypes.EVERYTHING_TYPE, | ||
| EntryTypes.FILE_DIR_TYPE, | ||
| EntryTypes.FILE_TYPE | ||
| ]); | ||
| const isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code); | ||
| const wantBigintFsStats = process.platform === "win32"; | ||
| const emptyFn = (_entryInfo) => true; | ||
| const normalizeFilter = (filter) => { | ||
| if (filter === void 0) return emptyFn; | ||
| if (typeof filter === "function") return filter; | ||
| if (typeof filter === "string") { | ||
| const fl = filter.trim(); | ||
| return (entry) => entry.basename === fl; | ||
| } | ||
| if (Array.isArray(filter)) { | ||
| const trItems = filter.map((item) => item.trim()); | ||
| return (entry) => trItems.some((f) => entry.basename === f); | ||
| } | ||
| return emptyFn; | ||
| }; | ||
| /** Readable readdir stream, emitting new files as they're being listed. */ | ||
| var ReaddirpStream = class extends Readable { | ||
| parents; | ||
| reading; | ||
| parent; | ||
| _stat; | ||
| _maxDepth; | ||
| _wantsDir; | ||
| _wantsFile; | ||
| _wantsEverything; | ||
| _root; | ||
| _isDirent; | ||
| _statsProp; | ||
| _rdOptions; | ||
| _fileFilter; | ||
| _directoryFilter; | ||
| constructor(options = {}) { | ||
| super({ | ||
| objectMode: true, | ||
| autoDestroy: true, | ||
| highWaterMark: options.highWaterMark | ||
| }); | ||
| const opts = { | ||
| ...defaultOptions, | ||
| ...options | ||
| }; | ||
| const { root, type: type$1 } = opts; | ||
| this._fileFilter = normalizeFilter(opts.fileFilter); | ||
| this._directoryFilter = normalizeFilter(opts.directoryFilter); | ||
| const statMethod = opts.lstat ? lstat : stat$1; | ||
| if (wantBigintFsStats) this._stat = (path$1) => statMethod(path$1, { bigint: true }); | ||
| else this._stat = statMethod; | ||
| this._maxDepth = opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth; | ||
| this._wantsDir = type$1 ? DIR_TYPES.has(type$1) : false; | ||
| this._wantsFile = type$1 ? FILE_TYPES.has(type$1) : false; | ||
| this._wantsEverything = type$1 === EntryTypes.EVERYTHING_TYPE; | ||
| this._root = resolve(root); | ||
| this._isDirent = !opts.alwaysStat; | ||
| this._statsProp = this._isDirent ? "dirent" : "stats"; | ||
| this._rdOptions = { | ||
| encoding: "utf8", | ||
| withFileTypes: this._isDirent | ||
| }; | ||
| this.parents = [this._exploreDir(root, 1)]; | ||
| this.reading = false; | ||
| this.parent = void 0; | ||
| } | ||
| async _read(batch) { | ||
| if (this.reading) return; | ||
| this.reading = true; | ||
| try { | ||
| while (!this.destroyed && batch > 0) { | ||
| const par = this.parent; | ||
| const fil = par && par.files; | ||
| if (fil && fil.length > 0) { | ||
| const { path: path$1, depth } = par; | ||
| const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path$1)); | ||
| const awaited = await Promise.all(slice); | ||
| for (const entry of awaited) { | ||
| if (!entry) continue; | ||
| if (this.destroyed) return; | ||
| const entryType = await this._getEntryType(entry); | ||
| if (entryType === "directory" && this._directoryFilter(entry)) { | ||
| if (depth <= this._maxDepth) this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); | ||
| if (this._wantsDir) { | ||
| this.push(entry); | ||
| batch--; | ||
| } | ||
| } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) { | ||
| if (this._wantsFile) { | ||
| this.push(entry); | ||
| batch--; | ||
| } | ||
| } | ||
| } | ||
| } else { | ||
| const parent = this.parents.pop(); | ||
| if (!parent) { | ||
| this.push(null); | ||
| break; | ||
| } | ||
| this.parent = await parent; | ||
| if (this.destroyed) return; | ||
| } | ||
| } | ||
| } catch (error) { | ||
| this.destroy(error); | ||
| } finally { | ||
| this.reading = false; | ||
| } | ||
| } | ||
| async _exploreDir(path$1, depth) { | ||
| let files; | ||
| try { | ||
| files = await readdir(path$1, this._rdOptions); | ||
| } catch (error) { | ||
| this._onError(error); | ||
| } | ||
| return { | ||
| files, | ||
| depth, | ||
| path: path$1 | ||
| }; | ||
| } | ||
| async _formatEntry(dirent, path$1) { | ||
| let entry; | ||
| const basename$1 = this._isDirent ? dirent.name : dirent; | ||
| try { | ||
| const fullPath = resolve(join(path$1, basename$1)); | ||
| entry = { | ||
| path: relative(this._root, fullPath), | ||
| fullPath, | ||
| basename: basename$1 | ||
| }; | ||
| entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); | ||
| } catch (err) { | ||
| this._onError(err); | ||
| return; | ||
| } | ||
| return entry; | ||
| } | ||
| _onError(err) { | ||
| if (isNormalFlowError(err) && !this.destroyed) this.emit("warn", err); | ||
| else this.destroy(err); | ||
| } | ||
| async _getEntryType(entry) { | ||
| if (!entry && this._statsProp in entry) return ""; | ||
| const stats = entry[this._statsProp]; | ||
| if (stats.isFile()) return "file"; | ||
| if (stats.isDirectory()) return "directory"; | ||
| if (stats && stats.isSymbolicLink()) { | ||
| const full = entry.fullPath; | ||
| try { | ||
| const entryRealPath = await realpath(full); | ||
| const entryRealPathStats = await lstat(entryRealPath); | ||
| if (entryRealPathStats.isFile()) return "file"; | ||
| if (entryRealPathStats.isDirectory()) { | ||
| const len = entryRealPath.length; | ||
| if (full.startsWith(entryRealPath) && full.substr(len, 1) === sep) { | ||
| const recursiveError = /* @__PURE__ */ new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`); | ||
| recursiveError.code = RECURSIVE_ERROR_CODE; | ||
| return this._onError(recursiveError); | ||
| } | ||
| return "directory"; | ||
| } | ||
| } catch (error) { | ||
| this._onError(error); | ||
| return ""; | ||
| } | ||
| } | ||
| } | ||
| _includeAsFile(entry) { | ||
| const stats = entry && entry[this._statsProp]; | ||
| return stats && this._wantsEverything && !stats.isDirectory(); | ||
| } | ||
| }; | ||
| /** | ||
| * Streaming version: Reads all files and directories in given root recursively. | ||
| * Consumes ~constant small amount of RAM. | ||
| * @param root Root directory | ||
| * @param options Options to specify root (start directory), filters and recursion depth | ||
| */ | ||
| function readdirp(root, options = {}) { | ||
| let type$1 = options.entryType || options.type; | ||
| if (type$1 === "both") type$1 = EntryTypes.FILE_DIR_TYPE; | ||
| if (type$1) options.type = type$1; | ||
| if (!root) throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)"); | ||
| else if (typeof root !== "string") throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)"); | ||
| else if (type$1 && !ALL_TYPES.includes(type$1)) throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`); | ||
| options.root = root; | ||
| return new ReaddirpStream(options); | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/handler.js | ||
| const STR_DATA = "data"; | ||
| const STR_END = "end"; | ||
| const STR_CLOSE = "close"; | ||
| const EMPTY_FN = () => {}; | ||
| const pl = process.platform; | ||
| const isWindows = pl === "win32"; | ||
| const isMacos = pl === "darwin"; | ||
| const isLinux = pl === "linux"; | ||
| const isFreeBSD = pl === "freebsd"; | ||
| const isIBMi = type() === "OS400"; | ||
| const EVENTS = { | ||
| ALL: "all", | ||
| READY: "ready", | ||
| ADD: "add", | ||
| CHANGE: "change", | ||
| ADD_DIR: "addDir", | ||
| UNLINK: "unlink", | ||
| UNLINK_DIR: "unlinkDir", | ||
| RAW: "raw", | ||
| ERROR: "error" | ||
| }; | ||
| const EV = EVENTS; | ||
| const THROTTLE_MODE_WATCH = "watch"; | ||
| const statMethods = { | ||
| lstat, | ||
| stat: stat$1 | ||
| }; | ||
| const KEY_LISTENERS = "listeners"; | ||
| const KEY_ERR = "errHandlers"; | ||
| const KEY_RAW = "rawEmitters"; | ||
| const HANDLER_KEYS = [ | ||
| KEY_LISTENERS, | ||
| KEY_ERR, | ||
| KEY_RAW | ||
| ]; | ||
| const binaryExtensions = new Set([ | ||
| "3dm", | ||
| "3ds", | ||
| "3g2", | ||
| "3gp", | ||
| "7z", | ||
| "a", | ||
| "aac", | ||
| "adp", | ||
| "afdesign", | ||
| "afphoto", | ||
| "afpub", | ||
| "ai", | ||
| "aif", | ||
| "aiff", | ||
| "alz", | ||
| "ape", | ||
| "apk", | ||
| "appimage", | ||
| "ar", | ||
| "arj", | ||
| "asf", | ||
| "au", | ||
| "avi", | ||
| "bak", | ||
| "baml", | ||
| "bh", | ||
| "bin", | ||
| "bk", | ||
| "bmp", | ||
| "btif", | ||
| "bz2", | ||
| "bzip2", | ||
| "cab", | ||
| "caf", | ||
| "cgm", | ||
| "class", | ||
| "cmx", | ||
| "cpio", | ||
| "cr2", | ||
| "cur", | ||
| "dat", | ||
| "dcm", | ||
| "deb", | ||
| "dex", | ||
| "djvu", | ||
| "dll", | ||
| "dmg", | ||
| "dng", | ||
| "doc", | ||
| "docm", | ||
| "docx", | ||
| "dot", | ||
| "dotm", | ||
| "dra", | ||
| "DS_Store", | ||
| "dsk", | ||
| "dts", | ||
| "dtshd", | ||
| "dvb", | ||
| "dwg", | ||
| "dxf", | ||
| "ecelp4800", | ||
| "ecelp7470", | ||
| "ecelp9600", | ||
| "egg", | ||
| "eol", | ||
| "eot", | ||
| "epub", | ||
| "exe", | ||
| "f4v", | ||
| "fbs", | ||
| "fh", | ||
| "fla", | ||
| "flac", | ||
| "flatpak", | ||
| "fli", | ||
| "flv", | ||
| "fpx", | ||
| "fst", | ||
| "fvt", | ||
| "g3", | ||
| "gh", | ||
| "gif", | ||
| "graffle", | ||
| "gz", | ||
| "gzip", | ||
| "h261", | ||
| "h263", | ||
| "h264", | ||
| "icns", | ||
| "ico", | ||
| "ief", | ||
| "img", | ||
| "ipa", | ||
| "iso", | ||
| "jar", | ||
| "jpeg", | ||
| "jpg", | ||
| "jpgv", | ||
| "jpm", | ||
| "jxr", | ||
| "key", | ||
| "ktx", | ||
| "lha", | ||
| "lib", | ||
| "lvp", | ||
| "lz", | ||
| "lzh", | ||
| "lzma", | ||
| "lzo", | ||
| "m3u", | ||
| "m4a", | ||
| "m4v", | ||
| "mar", | ||
| "mdi", | ||
| "mht", | ||
| "mid", | ||
| "midi", | ||
| "mj2", | ||
| "mka", | ||
| "mkv", | ||
| "mmr", | ||
| "mng", | ||
| "mobi", | ||
| "mov", | ||
| "movie", | ||
| "mp3", | ||
| "mp4", | ||
| "mp4a", | ||
| "mpeg", | ||
| "mpg", | ||
| "mpga", | ||
| "mxu", | ||
| "nef", | ||
| "npx", | ||
| "numbers", | ||
| "nupkg", | ||
| "o", | ||
| "odp", | ||
| "ods", | ||
| "odt", | ||
| "oga", | ||
| "ogg", | ||
| "ogv", | ||
| "otf", | ||
| "ott", | ||
| "pages", | ||
| "pbm", | ||
| "pcx", | ||
| "pdb", | ||
| "pdf", | ||
| "pea", | ||
| "pgm", | ||
| "pic", | ||
| "png", | ||
| "pnm", | ||
| "pot", | ||
| "potm", | ||
| "potx", | ||
| "ppa", | ||
| "ppam", | ||
| "ppm", | ||
| "pps", | ||
| "ppsm", | ||
| "ppsx", | ||
| "ppt", | ||
| "pptm", | ||
| "pptx", | ||
| "psd", | ||
| "pya", | ||
| "pyc", | ||
| "pyo", | ||
| "pyv", | ||
| "qt", | ||
| "rar", | ||
| "ras", | ||
| "raw", | ||
| "resources", | ||
| "rgb", | ||
| "rip", | ||
| "rlc", | ||
| "rmf", | ||
| "rmvb", | ||
| "rpm", | ||
| "rtf", | ||
| "rz", | ||
| "s3m", | ||
| "s7z", | ||
| "scpt", | ||
| "sgi", | ||
| "shar", | ||
| "snap", | ||
| "sil", | ||
| "sketch", | ||
| "slk", | ||
| "smv", | ||
| "snk", | ||
| "so", | ||
| "stl", | ||
| "suo", | ||
| "sub", | ||
| "swf", | ||
| "tar", | ||
| "tbz", | ||
| "tbz2", | ||
| "tga", | ||
| "tgz", | ||
| "thmx", | ||
| "tif", | ||
| "tiff", | ||
| "tlz", | ||
| "ttc", | ||
| "ttf", | ||
| "txz", | ||
| "udf", | ||
| "uvh", | ||
| "uvi", | ||
| "uvm", | ||
| "uvp", | ||
| "uvs", | ||
| "uvu", | ||
| "viv", | ||
| "vob", | ||
| "war", | ||
| "wav", | ||
| "wax", | ||
| "wbmp", | ||
| "wdp", | ||
| "weba", | ||
| "webm", | ||
| "webp", | ||
| "whl", | ||
| "wim", | ||
| "wm", | ||
| "wma", | ||
| "wmv", | ||
| "wmx", | ||
| "woff", | ||
| "woff2", | ||
| "wrm", | ||
| "wvx", | ||
| "xbm", | ||
| "xif", | ||
| "xla", | ||
| "xlam", | ||
| "xls", | ||
| "xlsb", | ||
| "xlsm", | ||
| "xlsx", | ||
| "xlt", | ||
| "xltm", | ||
| "xltx", | ||
| "xm", | ||
| "xmind", | ||
| "xpi", | ||
| "xpm", | ||
| "xwd", | ||
| "xz", | ||
| "z", | ||
| "zip", | ||
| "zipx" | ||
| ]); | ||
| const isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase()); | ||
| const foreach = (val, fn) => { | ||
| if (val instanceof Set) val.forEach(fn); | ||
| else fn(val); | ||
| }; | ||
| const addAndConvert = (main, prop, item) => { | ||
| let container = main[prop]; | ||
| if (!(container instanceof Set)) main[prop] = container = new Set([container]); | ||
| container.add(item); | ||
| }; | ||
| const clearItem = (cont) => (key) => { | ||
| const set = cont[key]; | ||
| if (set instanceof Set) set.clear(); | ||
| else delete cont[key]; | ||
| }; | ||
| const delFromSet = (main, prop, item) => { | ||
| const container = main[prop]; | ||
| if (container instanceof Set) container.delete(item); | ||
| else if (container === item) delete main[prop]; | ||
| }; | ||
| const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; | ||
| const FsWatchInstances = /* @__PURE__ */ new Map(); | ||
| /** | ||
| * Instantiates the fs_watch interface | ||
| * @param path to be watched | ||
| * @param options to be passed to fs_watch | ||
| * @param listener main event handler | ||
| * @param errHandler emits info about errors | ||
| * @param emitRaw emits raw event data | ||
| * @returns {NativeFsWatcher} | ||
| */ | ||
| function createFsWatchInstance(path$1, options, listener, errHandler, emitRaw) { | ||
| const handleEvent = (rawEvent, evPath) => { | ||
| listener(path$1); | ||
| emitRaw(rawEvent, evPath, { watchedPath: path$1 }); | ||
| if (evPath && path$1 !== evPath) fsWatchBroadcast(sp.resolve(path$1, evPath), KEY_LISTENERS, sp.join(path$1, evPath)); | ||
| }; | ||
| try { | ||
| return watch(path$1, { persistent: options.persistent }, handleEvent); | ||
| } catch (error) { | ||
| errHandler(error); | ||
| return; | ||
| } | ||
| } | ||
| /** | ||
| * Helper for passing fs_watch event data to a collection of listeners | ||
| * @param fullPath absolute path bound to fs_watch instance | ||
| */ | ||
| const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => { | ||
| const cont = FsWatchInstances.get(fullPath); | ||
| if (!cont) return; | ||
| foreach(cont[listenerType], (listener) => { | ||
| listener(val1, val2, val3); | ||
| }); | ||
| }; | ||
| /** | ||
| * Instantiates the fs_watch interface or binds listeners | ||
| * to an existing one covering the same file system entry | ||
| * @param path | ||
| * @param fullPath absolute path | ||
| * @param options to be passed to fs_watch | ||
| * @param handlers container for event listener functions | ||
| */ | ||
| const setFsWatchListener = (path$1, fullPath, options, handlers) => { | ||
| const { listener, errHandler, rawEmitter } = handlers; | ||
| let cont = FsWatchInstances.get(fullPath); | ||
| let watcher; | ||
| if (!options.persistent) { | ||
| watcher = createFsWatchInstance(path$1, options, listener, errHandler, rawEmitter); | ||
| if (!watcher) return; | ||
| return watcher.close.bind(watcher); | ||
| } | ||
| if (cont) { | ||
| addAndConvert(cont, KEY_LISTENERS, listener); | ||
| addAndConvert(cont, KEY_ERR, errHandler); | ||
| addAndConvert(cont, KEY_RAW, rawEmitter); | ||
| } else { | ||
| watcher = createFsWatchInstance(path$1, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW)); | ||
| if (!watcher) return; | ||
| watcher.on(EV.ERROR, async (error) => { | ||
| const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); | ||
| if (cont) cont.watcherUnusable = true; | ||
| if (isWindows && error.code === "EPERM") try { | ||
| await (await open(path$1, "r")).close(); | ||
| broadcastErr(error); | ||
| } catch (err) {} | ||
| else broadcastErr(error); | ||
| }); | ||
| cont = { | ||
| listeners: listener, | ||
| errHandlers: errHandler, | ||
| rawEmitters: rawEmitter, | ||
| watcher | ||
| }; | ||
| FsWatchInstances.set(fullPath, cont); | ||
| } | ||
| return () => { | ||
| delFromSet(cont, KEY_LISTENERS, listener); | ||
| delFromSet(cont, KEY_ERR, errHandler); | ||
| delFromSet(cont, KEY_RAW, rawEmitter); | ||
| if (isEmptySet(cont.listeners)) { | ||
| cont.watcher.close(); | ||
| FsWatchInstances.delete(fullPath); | ||
| HANDLER_KEYS.forEach(clearItem(cont)); | ||
| cont.watcher = void 0; | ||
| Object.freeze(cont); | ||
| } | ||
| }; | ||
| }; | ||
| const FsWatchFileInstances = /* @__PURE__ */ new Map(); | ||
| /** | ||
| * Instantiates the fs_watchFile interface or binds listeners | ||
| * to an existing one covering the same file system entry | ||
| * @param path to be watched | ||
| * @param fullPath absolute path | ||
| * @param options options to be passed to fs_watchFile | ||
| * @param handlers container for event listener functions | ||
| * @returns closer | ||
| */ | ||
| const setFsWatchFileListener = (path$1, fullPath, options, handlers) => { | ||
| const { listener, rawEmitter } = handlers; | ||
| let cont = FsWatchFileInstances.get(fullPath); | ||
| const copts = cont && cont.options; | ||
| if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { | ||
| unwatchFile(fullPath); | ||
| cont = void 0; | ||
| } | ||
| if (cont) { | ||
| addAndConvert(cont, KEY_LISTENERS, listener); | ||
| addAndConvert(cont, KEY_RAW, rawEmitter); | ||
| } else { | ||
| cont = { | ||
| listeners: listener, | ||
| rawEmitters: rawEmitter, | ||
| options, | ||
| watcher: watchFile(fullPath, options, (curr, prev) => { | ||
| foreach(cont.rawEmitters, (rawEmitter$1) => { | ||
| rawEmitter$1(EV.CHANGE, fullPath, { | ||
| curr, | ||
| prev | ||
| }); | ||
| }); | ||
| const currmtime = curr.mtimeMs; | ||
| if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) foreach(cont.listeners, (listener$1) => listener$1(path$1, curr)); | ||
| }) | ||
| }; | ||
| FsWatchFileInstances.set(fullPath, cont); | ||
| } | ||
| return () => { | ||
| delFromSet(cont, KEY_LISTENERS, listener); | ||
| delFromSet(cont, KEY_RAW, rawEmitter); | ||
| if (isEmptySet(cont.listeners)) { | ||
| FsWatchFileInstances.delete(fullPath); | ||
| unwatchFile(fullPath); | ||
| cont.options = cont.watcher = void 0; | ||
| Object.freeze(cont); | ||
| } | ||
| }; | ||
| }; | ||
| /** | ||
| * @mixin | ||
| */ | ||
| var NodeFsHandler = class { | ||
| fsw; | ||
| _boundHandleError; | ||
| constructor(fsW) { | ||
| this.fsw = fsW; | ||
| this._boundHandleError = (error) => fsW._handleError(error); | ||
| } | ||
| /** | ||
| * Watch file for changes with fs_watchFile or fs_watch. | ||
| * @param path to file or dir | ||
| * @param listener on fs change | ||
| * @returns closer for the watcher instance | ||
| */ | ||
| _watchWithNodeFs(path$1, listener) { | ||
| const opts = this.fsw.options; | ||
| const directory = sp.dirname(path$1); | ||
| const basename$1 = sp.basename(path$1); | ||
| this.fsw._getWatchedDir(directory).add(basename$1); | ||
| const absolutePath = sp.resolve(path$1); | ||
| const options = { persistent: opts.persistent }; | ||
| if (!listener) listener = EMPTY_FN; | ||
| let closer; | ||
| if (opts.usePolling) { | ||
| options.interval = opts.interval !== opts.binaryInterval && isBinaryPath(basename$1) ? opts.binaryInterval : opts.interval; | ||
| closer = setFsWatchFileListener(path$1, absolutePath, options, { | ||
| listener, | ||
| rawEmitter: this.fsw._emitRaw | ||
| }); | ||
| } else closer = setFsWatchListener(path$1, absolutePath, options, { | ||
| listener, | ||
| errHandler: this._boundHandleError, | ||
| rawEmitter: this.fsw._emitRaw | ||
| }); | ||
| return closer; | ||
| } | ||
| /** | ||
| * Watch a file and emit add event if warranted. | ||
| * @returns closer for the watcher instance | ||
| */ | ||
| _handleFile(file, stats, initialAdd) { | ||
| if (this.fsw.closed) return; | ||
| const dirname$1 = sp.dirname(file); | ||
| const basename$1 = sp.basename(file); | ||
| const parent = this.fsw._getWatchedDir(dirname$1); | ||
| let prevStats = stats; | ||
| if (parent.has(basename$1)) return; | ||
| const listener = async (path$1, newStats) => { | ||
| if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return; | ||
| if (!newStats || newStats.mtimeMs === 0) try { | ||
| const newStats$1 = await stat$1(file); | ||
| if (this.fsw.closed) return; | ||
| const at = newStats$1.atimeMs; | ||
| const mt = newStats$1.mtimeMs; | ||
| if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats$1); | ||
| if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats$1.ino) { | ||
| this.fsw._closeFile(path$1); | ||
| prevStats = newStats$1; | ||
| const closer$1 = this._watchWithNodeFs(file, listener); | ||
| if (closer$1) this.fsw._addPathCloser(path$1, closer$1); | ||
| } else prevStats = newStats$1; | ||
| } catch (error) { | ||
| this.fsw._remove(dirname$1, basename$1); | ||
| } | ||
| else if (parent.has(basename$1)) { | ||
| const at = newStats.atimeMs; | ||
| const mt = newStats.mtimeMs; | ||
| if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats); | ||
| prevStats = newStats; | ||
| } | ||
| }; | ||
| const closer = this._watchWithNodeFs(file, listener); | ||
| if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) { | ||
| if (!this.fsw._throttle(EV.ADD, file, 0)) return; | ||
| this.fsw._emit(EV.ADD, file, stats); | ||
| } | ||
| return closer; | ||
| } | ||
| /** | ||
| * Handle symlinks encountered while reading a dir. | ||
| * @param entry returned by readdirp | ||
| * @param directory path of dir being read | ||
| * @param path of this item | ||
| * @param item basename of this item | ||
| * @returns true if no more processing is needed for this entry. | ||
| */ | ||
| async _handleSymlink(entry, directory, path$1, item) { | ||
| if (this.fsw.closed) return; | ||
| const full = entry.fullPath; | ||
| const dir = this.fsw._getWatchedDir(directory); | ||
| if (!this.fsw.options.followSymlinks) { | ||
| this.fsw._incrReadyCount(); | ||
| let linkPath; | ||
| try { | ||
| linkPath = await realpath(path$1); | ||
| } catch (e) { | ||
| this.fsw._emitReady(); | ||
| return true; | ||
| } | ||
| if (this.fsw.closed) return; | ||
| if (dir.has(item)) { | ||
| if (this.fsw._symlinkPaths.get(full) !== linkPath) { | ||
| this.fsw._symlinkPaths.set(full, linkPath); | ||
| this.fsw._emit(EV.CHANGE, path$1, entry.stats); | ||
| } | ||
| } else { | ||
| dir.add(item); | ||
| this.fsw._symlinkPaths.set(full, linkPath); | ||
| this.fsw._emit(EV.ADD, path$1, entry.stats); | ||
| } | ||
| this.fsw._emitReady(); | ||
| return true; | ||
| } | ||
| if (this.fsw._symlinkPaths.has(full)) return true; | ||
| this.fsw._symlinkPaths.set(full, true); | ||
| } | ||
| _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { | ||
| directory = sp.join(directory, ""); | ||
| const throttleKey = target ? `${directory}:${target}` : directory; | ||
| throttler = this.fsw._throttle("readdir", throttleKey, 1e3); | ||
| if (!throttler) return; | ||
| const previous = this.fsw._getWatchedDir(wh.path); | ||
| const current = /* @__PURE__ */ new Set(); | ||
| let stream = this.fsw._readdirp(directory, { | ||
| fileFilter: (entry) => wh.filterPath(entry), | ||
| directoryFilter: (entry) => wh.filterDir(entry) | ||
| }); | ||
| if (!stream) return; | ||
| stream.on(STR_DATA, async (entry) => { | ||
| if (this.fsw.closed) { | ||
| stream = void 0; | ||
| return; | ||
| } | ||
| const item = entry.path; | ||
| let path$1 = sp.join(directory, item); | ||
| current.add(item); | ||
| if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path$1, item)) return; | ||
| if (this.fsw.closed) { | ||
| stream = void 0; | ||
| return; | ||
| } | ||
| if (item === target || !target && !previous.has(item)) { | ||
| this.fsw._incrReadyCount(); | ||
| path$1 = sp.join(dir, sp.relative(dir, path$1)); | ||
| this._addToNodeFs(path$1, initialAdd, wh, depth + 1); | ||
| } | ||
| }).on(EV.ERROR, this._boundHandleError); | ||
| return new Promise((resolve$1, reject) => { | ||
| if (!stream) return reject(); | ||
| stream.once(STR_END, () => { | ||
| if (this.fsw.closed) { | ||
| stream = void 0; | ||
| return; | ||
| } | ||
| const wasThrottled = throttler ? throttler.clear() : false; | ||
| resolve$1(void 0); | ||
| previous.getChildren().filter((item) => { | ||
| return item !== directory && !current.has(item); | ||
| }).forEach((item) => { | ||
| this.fsw._remove(directory, item); | ||
| }); | ||
| stream = void 0; | ||
| if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler); | ||
| }); | ||
| }); | ||
| } | ||
| /** | ||
| * Read directory to add / remove files from `@watched` list and re-read it on change. | ||
| * @param dir fs path | ||
| * @param stats | ||
| * @param initialAdd | ||
| * @param depth relative to user-supplied path | ||
| * @param target child path targeted for watch | ||
| * @param wh Common watch helpers for this path | ||
| * @param realpath | ||
| * @returns closer for the watcher instance. | ||
| */ | ||
| async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath$1) { | ||
| const parentDir = this.fsw._getWatchedDir(sp.dirname(dir)); | ||
| const tracked = parentDir.has(sp.basename(dir)); | ||
| if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) this.fsw._emit(EV.ADD_DIR, dir, stats); | ||
| parentDir.add(sp.basename(dir)); | ||
| this.fsw._getWatchedDir(dir); | ||
| let throttler; | ||
| let closer; | ||
| const oDepth = this.fsw.options.depth; | ||
| if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath$1)) { | ||
| if (!target) { | ||
| await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); | ||
| if (this.fsw.closed) return; | ||
| } | ||
| closer = this._watchWithNodeFs(dir, (dirPath, stats$1) => { | ||
| if (stats$1 && stats$1.mtimeMs === 0) return; | ||
| this._handleRead(dirPath, false, wh, target, dir, depth, throttler); | ||
| }); | ||
| } | ||
| return closer; | ||
| } | ||
| /** | ||
| * Handle added file, directory, or glob pattern. | ||
| * Delegates call to _handleFile / _handleDir after checks. | ||
| * @param path to file or ir | ||
| * @param initialAdd was the file added at watch instantiation? | ||
| * @param priorWh depth relative to user-supplied path | ||
| * @param depth Child path actually targeted for watch | ||
| * @param target Child path actually targeted for watch | ||
| */ | ||
| async _addToNodeFs(path$1, initialAdd, priorWh, depth, target) { | ||
| const ready = this.fsw._emitReady; | ||
| if (this.fsw._isIgnored(path$1) || this.fsw.closed) { | ||
| ready(); | ||
| return false; | ||
| } | ||
| const wh = this.fsw._getWatchHelpers(path$1); | ||
| if (priorWh) { | ||
| wh.filterPath = (entry) => priorWh.filterPath(entry); | ||
| wh.filterDir = (entry) => priorWh.filterDir(entry); | ||
| } | ||
| try { | ||
| const stats = await statMethods[wh.statMethod](wh.watchPath); | ||
| if (this.fsw.closed) return; | ||
| if (this.fsw._isIgnored(wh.watchPath, stats)) { | ||
| ready(); | ||
| return false; | ||
| } | ||
| const follow = this.fsw.options.followSymlinks; | ||
| let closer; | ||
| if (stats.isDirectory()) { | ||
| const absPath = sp.resolve(path$1); | ||
| const targetPath = follow ? await realpath(path$1) : path$1; | ||
| if (this.fsw.closed) return; | ||
| closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); | ||
| if (this.fsw.closed) return; | ||
| if (absPath !== targetPath && targetPath !== void 0) this.fsw._symlinkPaths.set(absPath, targetPath); | ||
| } else if (stats.isSymbolicLink()) { | ||
| const targetPath = follow ? await realpath(path$1) : path$1; | ||
| if (this.fsw.closed) return; | ||
| const parent = sp.dirname(wh.watchPath); | ||
| this.fsw._getWatchedDir(parent).add(wh.watchPath); | ||
| this.fsw._emit(EV.ADD, wh.watchPath, stats); | ||
| closer = await this._handleDir(parent, stats, initialAdd, depth, path$1, wh, targetPath); | ||
| if (this.fsw.closed) return; | ||
| if (targetPath !== void 0) this.fsw._symlinkPaths.set(sp.resolve(path$1), targetPath); | ||
| } else closer = this._handleFile(wh.watchPath, stats, initialAdd); | ||
| ready(); | ||
| if (closer) this.fsw._addPathCloser(path$1, closer); | ||
| return false; | ||
| } catch (error) { | ||
| if (this.fsw._handleError(error)) { | ||
| ready(); | ||
| return path$1; | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/index.js | ||
| /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */ | ||
| var chokidar_exports = /* @__PURE__ */ __exportAll({ | ||
| FSWatcher: () => FSWatcher, | ||
| WatchHelper: () => WatchHelper, | ||
| default: () => chokidar_default, | ||
| watch: () => watch$1 | ||
| }); | ||
| const SLASH = "/"; | ||
| const SLASH_SLASH = "//"; | ||
| const ONE_DOT = "."; | ||
| const TWO_DOTS = ".."; | ||
| const STRING_TYPE = "string"; | ||
| const BACK_SLASH_RE = /\\/g; | ||
| const DOUBLE_SLASH_RE = /\/\//g; | ||
| const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; | ||
| const REPLACER_RE = /^\.[/\\]/; | ||
| function arrify(item) { | ||
| return Array.isArray(item) ? item : [item]; | ||
| } | ||
| const isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp); | ||
| function createPattern(matcher) { | ||
| if (typeof matcher === "function") return matcher; | ||
| if (typeof matcher === "string") return (string) => matcher === string; | ||
| if (matcher instanceof RegExp) return (string) => matcher.test(string); | ||
| if (typeof matcher === "object" && matcher !== null) return (string) => { | ||
| if (matcher.path === string) return true; | ||
| if (matcher.recursive) { | ||
| const relative$1 = sp.relative(matcher.path, string); | ||
| if (!relative$1) return false; | ||
| return !relative$1.startsWith("..") && !sp.isAbsolute(relative$1); | ||
| } | ||
| return false; | ||
| }; | ||
| return () => false; | ||
| } | ||
| function normalizePath(path$1) { | ||
| if (typeof path$1 !== "string") throw new Error("string expected"); | ||
| path$1 = sp.normalize(path$1); | ||
| path$1 = path$1.replace(/\\/g, "/"); | ||
| let prepend = false; | ||
| if (path$1.startsWith("//")) prepend = true; | ||
| path$1 = path$1.replace(DOUBLE_SLASH_RE, "/"); | ||
| if (prepend) path$1 = "/" + path$1; | ||
| return path$1; | ||
| } | ||
| function matchPatterns(patterns, testString, stats) { | ||
| const path$1 = normalizePath(testString); | ||
| for (let index = 0; index < patterns.length; index++) { | ||
| const pattern = patterns[index]; | ||
| if (pattern(path$1, stats)) return true; | ||
| } | ||
| return false; | ||
| } | ||
| function anymatch(matchers, testString) { | ||
| if (matchers == null) throw new TypeError("anymatch: specify first argument"); | ||
| const patterns = arrify(matchers).map((matcher) => createPattern(matcher)); | ||
| if (testString == null) return (testString$1, stats) => { | ||
| return matchPatterns(patterns, testString$1, stats); | ||
| }; | ||
| return matchPatterns(patterns, testString); | ||
| } | ||
| const unifyPaths = (paths_) => { | ||
| const paths = arrify(paths_).flat(); | ||
| if (!paths.every((p) => typeof p === STRING_TYPE)) throw new TypeError(`Non-string provided as watch path: ${paths}`); | ||
| return paths.map(normalizePathToUnix); | ||
| }; | ||
| const toUnix = (string) => { | ||
| let str = string.replace(BACK_SLASH_RE, SLASH); | ||
| let prepend = false; | ||
| if (str.startsWith(SLASH_SLASH)) prepend = true; | ||
| str = str.replace(DOUBLE_SLASH_RE, SLASH); | ||
| if (prepend) str = SLASH + str; | ||
| return str; | ||
| }; | ||
| const normalizePathToUnix = (path$1) => toUnix(sp.normalize(toUnix(path$1))); | ||
| const normalizeIgnored = (cwd = "") => (path$1) => { | ||
| if (typeof path$1 === "string") return normalizePathToUnix(sp.isAbsolute(path$1) ? path$1 : sp.join(cwd, path$1)); | ||
| else return path$1; | ||
| }; | ||
| const getAbsolutePath = (path$1, cwd) => { | ||
| if (sp.isAbsolute(path$1)) return path$1; | ||
| return sp.join(cwd, path$1); | ||
| }; | ||
| const EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set()); | ||
| /** | ||
| * Directory entry. | ||
| */ | ||
| var DirEntry = class { | ||
| path; | ||
| _removeWatcher; | ||
| items; | ||
| constructor(dir, removeWatcher) { | ||
| this.path = dir; | ||
| this._removeWatcher = removeWatcher; | ||
| this.items = /* @__PURE__ */ new Set(); | ||
| } | ||
| add(item) { | ||
| const { items } = this; | ||
| if (!items) return; | ||
| if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item); | ||
| } | ||
| async remove(item) { | ||
| const { items } = this; | ||
| if (!items) return; | ||
| items.delete(item); | ||
| if (items.size > 0) return; | ||
| const dir = this.path; | ||
| try { | ||
| await readdir(dir); | ||
| } catch (err) { | ||
| if (this._removeWatcher) this._removeWatcher(sp.dirname(dir), sp.basename(dir)); | ||
| } | ||
| } | ||
| has(item) { | ||
| const { items } = this; | ||
| if (!items) return; | ||
| return items.has(item); | ||
| } | ||
| getChildren() { | ||
| const { items } = this; | ||
| if (!items) return []; | ||
| return [...items.values()]; | ||
| } | ||
| dispose() { | ||
| this.items.clear(); | ||
| this.path = ""; | ||
| this._removeWatcher = EMPTY_FN; | ||
| this.items = EMPTY_SET; | ||
| Object.freeze(this); | ||
| } | ||
| }; | ||
| const STAT_METHOD_F = "stat"; | ||
| const STAT_METHOD_L = "lstat"; | ||
| var WatchHelper = class { | ||
| fsw; | ||
| path; | ||
| watchPath; | ||
| fullWatchPath; | ||
| dirParts; | ||
| followSymlinks; | ||
| statMethod; | ||
| constructor(path$1, follow, fsw) { | ||
| this.fsw = fsw; | ||
| const watchPath = path$1; | ||
| this.path = path$1 = path$1.replace(REPLACER_RE, ""); | ||
| this.watchPath = watchPath; | ||
| this.fullWatchPath = sp.resolve(watchPath); | ||
| this.dirParts = []; | ||
| this.dirParts.forEach((parts) => { | ||
| if (parts.length > 1) parts.pop(); | ||
| }); | ||
| this.followSymlinks = follow; | ||
| this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; | ||
| } | ||
| entryPath(entry) { | ||
| return sp.join(this.watchPath, sp.relative(this.watchPath, entry.fullPath)); | ||
| } | ||
| filterPath(entry) { | ||
| const { stats } = entry; | ||
| if (stats && stats.isSymbolicLink()) return this.filterDir(entry); | ||
| const resolvedPath = this.entryPath(entry); | ||
| return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats); | ||
| } | ||
| filterDir(entry) { | ||
| return this.fsw._isntIgnored(this.entryPath(entry), entry.stats); | ||
| } | ||
| }; | ||
| /** | ||
| * Watches files & directories for changes. Emitted events: | ||
| * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error` | ||
| * | ||
| * new FSWatcher() | ||
| * .add(directories) | ||
| * .on('add', path => log('File', path, 'was added')) | ||
| */ | ||
| var FSWatcher = class extends EventEmitter { | ||
| closed; | ||
| options; | ||
| _closers; | ||
| _ignoredPaths; | ||
| _throttled; | ||
| _streams; | ||
| _symlinkPaths; | ||
| _watched; | ||
| _pendingWrites; | ||
| _pendingUnlinks; | ||
| _readyCount; | ||
| _emitReady; | ||
| _closePromise; | ||
| _userIgnored; | ||
| _readyEmitted; | ||
| _emitRaw; | ||
| _boundRemove; | ||
| _nodeFsHandler; | ||
| constructor(_opts = {}) { | ||
| super(); | ||
| this.closed = false; | ||
| this._closers = /* @__PURE__ */ new Map(); | ||
| this._ignoredPaths = /* @__PURE__ */ new Set(); | ||
| this._throttled = /* @__PURE__ */ new Map(); | ||
| this._streams = /* @__PURE__ */ new Set(); | ||
| this._symlinkPaths = /* @__PURE__ */ new Map(); | ||
| this._watched = /* @__PURE__ */ new Map(); | ||
| this._pendingWrites = /* @__PURE__ */ new Map(); | ||
| this._pendingUnlinks = /* @__PURE__ */ new Map(); | ||
| this._readyCount = 0; | ||
| this._readyEmitted = false; | ||
| const awf = _opts.awaitWriteFinish; | ||
| const DEF_AWF = { | ||
| stabilityThreshold: 2e3, | ||
| pollInterval: 100 | ||
| }; | ||
| const opts = { | ||
| persistent: true, | ||
| ignoreInitial: false, | ||
| ignorePermissionErrors: false, | ||
| interval: 100, | ||
| binaryInterval: 300, | ||
| followSymlinks: true, | ||
| usePolling: false, | ||
| atomic: true, | ||
| ..._opts, | ||
| ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]), | ||
| awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { | ||
| ...DEF_AWF, | ||
| ...awf | ||
| } : false | ||
| }; | ||
| if (isIBMi) opts.usePolling = true; | ||
| if (opts.atomic === void 0) opts.atomic = !opts.usePolling; | ||
| const envPoll = process.env.CHOKIDAR_USEPOLLING; | ||
| if (envPoll !== void 0) { | ||
| const envLower = envPoll.toLowerCase(); | ||
| if (envLower === "false" || envLower === "0") opts.usePolling = false; | ||
| else if (envLower === "true" || envLower === "1") opts.usePolling = true; | ||
| else opts.usePolling = !!envLower; | ||
| } | ||
| const envInterval = process.env.CHOKIDAR_INTERVAL; | ||
| if (envInterval) opts.interval = Number.parseInt(envInterval, 10); | ||
| let readyCalls = 0; | ||
| this._emitReady = () => { | ||
| readyCalls++; | ||
| if (readyCalls >= this._readyCount) { | ||
| this._emitReady = EMPTY_FN; | ||
| this._readyEmitted = true; | ||
| process.nextTick(() => this.emit(EVENTS.READY)); | ||
| } | ||
| }; | ||
| this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args); | ||
| this._boundRemove = this._remove.bind(this); | ||
| this.options = opts; | ||
| this._nodeFsHandler = new NodeFsHandler(this); | ||
| Object.freeze(opts); | ||
| } | ||
| _addIgnoredPath(matcher) { | ||
| if (isMatcherObject(matcher)) { | ||
| for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) return; | ||
| } | ||
| this._ignoredPaths.add(matcher); | ||
| } | ||
| _removeIgnoredPath(matcher) { | ||
| this._ignoredPaths.delete(matcher); | ||
| if (typeof matcher === "string") { | ||
| for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher) this._ignoredPaths.delete(ignored); | ||
| } | ||
| } | ||
| /** | ||
| * Adds paths to be watched on an existing FSWatcher instance. | ||
| * @param paths_ file or file list. Other arguments are unused | ||
| */ | ||
| add(paths_, _origAdd, _internal) { | ||
| const { cwd } = this.options; | ||
| this.closed = false; | ||
| this._closePromise = void 0; | ||
| let paths = unifyPaths(paths_); | ||
| if (cwd) paths = paths.map((path$1) => { | ||
| return getAbsolutePath(path$1, cwd); | ||
| }); | ||
| paths.forEach((path$1) => { | ||
| this._removeIgnoredPath(path$1); | ||
| }); | ||
| this._userIgnored = void 0; | ||
| if (!this._readyCount) this._readyCount = 0; | ||
| this._readyCount += paths.length; | ||
| Promise.all(paths.map(async (path$1) => { | ||
| const res = await this._nodeFsHandler._addToNodeFs(path$1, !_internal, void 0, 0, _origAdd); | ||
| if (res) this._emitReady(); | ||
| return res; | ||
| })).then((results) => { | ||
| if (this.closed) return; | ||
| results.forEach((item) => { | ||
| if (item) this.add(sp.dirname(item), sp.basename(_origAdd || item)); | ||
| }); | ||
| }); | ||
| return this; | ||
| } | ||
| /** | ||
| * Close watchers or start ignoring events from specified paths. | ||
| */ | ||
| unwatch(paths_) { | ||
| if (this.closed) return this; | ||
| const paths = unifyPaths(paths_); | ||
| const { cwd } = this.options; | ||
| paths.forEach((path$1) => { | ||
| if (!sp.isAbsolute(path$1) && !this._closers.has(path$1)) { | ||
| if (cwd) path$1 = sp.join(cwd, path$1); | ||
| path$1 = sp.resolve(path$1); | ||
| } | ||
| this._closePath(path$1); | ||
| this._addIgnoredPath(path$1); | ||
| if (this._watched.has(path$1)) this._addIgnoredPath({ | ||
| path: path$1, | ||
| recursive: true | ||
| }); | ||
| this._userIgnored = void 0; | ||
| }); | ||
| return this; | ||
| } | ||
| /** | ||
| * Close watchers and remove all listeners from watched paths. | ||
| */ | ||
| close() { | ||
| if (this._closePromise) return this._closePromise; | ||
| this.closed = true; | ||
| this.removeAllListeners(); | ||
| const closers = []; | ||
| this._closers.forEach((closerList) => closerList.forEach((closer) => { | ||
| const promise = closer(); | ||
| if (promise instanceof Promise) closers.push(promise); | ||
| })); | ||
| this._streams.forEach((stream) => stream.destroy()); | ||
| this._userIgnored = void 0; | ||
| this._readyCount = 0; | ||
| this._readyEmitted = false; | ||
| this._watched.forEach((dirent) => dirent.dispose()); | ||
| this._closers.clear(); | ||
| this._watched.clear(); | ||
| this._streams.clear(); | ||
| this._symlinkPaths.clear(); | ||
| this._throttled.clear(); | ||
| this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve(); | ||
| return this._closePromise; | ||
| } | ||
| /** | ||
| * Expose list of watched paths | ||
| * @returns for chaining | ||
| */ | ||
| getWatched() { | ||
| const watchList = {}; | ||
| this._watched.forEach((entry, dir) => { | ||
| const index = (this.options.cwd ? sp.relative(this.options.cwd, dir) : dir) || ONE_DOT; | ||
| watchList[index] = entry.getChildren().sort(); | ||
| }); | ||
| return watchList; | ||
| } | ||
| emitWithAll(event, args) { | ||
| this.emit(event, ...args); | ||
| if (event !== EVENTS.ERROR) this.emit(EVENTS.ALL, event, ...args); | ||
| } | ||
| /** | ||
| * Normalize and emit events. | ||
| * Calling _emit DOES NOT MEAN emit() would be called! | ||
| * @param event Type of event | ||
| * @param path File or directory path | ||
| * @param stats arguments to be passed with event | ||
| * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag | ||
| */ | ||
| async _emit(event, path$1, stats) { | ||
| if (this.closed) return; | ||
| const opts = this.options; | ||
| if (isWindows) path$1 = sp.normalize(path$1); | ||
| if (opts.cwd) path$1 = sp.relative(opts.cwd, path$1); | ||
| const args = [path$1]; | ||
| if (stats != null) args.push(stats); | ||
| const awf = opts.awaitWriteFinish; | ||
| let pw; | ||
| if (awf && (pw = this._pendingWrites.get(path$1))) { | ||
| pw.lastChange = /* @__PURE__ */ new Date(); | ||
| return this; | ||
| } | ||
| if (opts.atomic) { | ||
| if (event === EVENTS.UNLINK) { | ||
| this._pendingUnlinks.set(path$1, [event, ...args]); | ||
| setTimeout(() => { | ||
| this._pendingUnlinks.forEach((entry, path$2) => { | ||
| this.emit(...entry); | ||
| this.emit(EVENTS.ALL, ...entry); | ||
| this._pendingUnlinks.delete(path$2); | ||
| }); | ||
| }, typeof opts.atomic === "number" ? opts.atomic : 100); | ||
| return this; | ||
| } | ||
| if (event === EVENTS.ADD && this._pendingUnlinks.has(path$1)) { | ||
| event = EVENTS.CHANGE; | ||
| this._pendingUnlinks.delete(path$1); | ||
| } | ||
| } | ||
| if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) { | ||
| const awfEmit = (err, stats$1) => { | ||
| if (err) { | ||
| event = EVENTS.ERROR; | ||
| args[0] = err; | ||
| this.emitWithAll(event, args); | ||
| } else if (stats$1) { | ||
| if (args.length > 1) args[1] = stats$1; | ||
| else args.push(stats$1); | ||
| this.emitWithAll(event, args); | ||
| } | ||
| }; | ||
| this._awaitWriteFinish(path$1, awf.stabilityThreshold, event, awfEmit); | ||
| return this; | ||
| } | ||
| if (event === EVENTS.CHANGE) { | ||
| if (!this._throttle(EVENTS.CHANGE, path$1, 50)) return this; | ||
| } | ||
| if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) { | ||
| const fullPath = opts.cwd ? sp.join(opts.cwd, path$1) : path$1; | ||
| let stats$1; | ||
| try { | ||
| stats$1 = await stat$1(fullPath); | ||
| } catch (err) {} | ||
| if (!stats$1 || this.closed) return; | ||
| args.push(stats$1); | ||
| } | ||
| this.emitWithAll(event, args); | ||
| return this; | ||
| } | ||
| /** | ||
| * Common handler for errors | ||
| * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag | ||
| */ | ||
| _handleError(error) { | ||
| const code = error && error.code; | ||
| if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) this.emit(EVENTS.ERROR, error); | ||
| return error || this.closed; | ||
| } | ||
| /** | ||
| * Helper utility for throttling | ||
| * @param actionType type being throttled | ||
| * @param path being acted upon | ||
| * @param timeout duration of time to suppress duplicate actions | ||
| * @returns tracking object or false if action should be suppressed | ||
| */ | ||
| _throttle(actionType, path$1, timeout) { | ||
| if (!this._throttled.has(actionType)) this._throttled.set(actionType, /* @__PURE__ */ new Map()); | ||
| const action = this._throttled.get(actionType); | ||
| if (!action) throw new Error("invalid throttle"); | ||
| const actionPath = action.get(path$1); | ||
| if (actionPath) { | ||
| actionPath.count++; | ||
| return false; | ||
| } | ||
| let timeoutObject; | ||
| const clear = () => { | ||
| const item = action.get(path$1); | ||
| const count = item ? item.count : 0; | ||
| action.delete(path$1); | ||
| clearTimeout(timeoutObject); | ||
| if (item) clearTimeout(item.timeoutObject); | ||
| return count; | ||
| }; | ||
| timeoutObject = setTimeout(clear, timeout); | ||
| const thr = { | ||
| timeoutObject, | ||
| clear, | ||
| count: 0 | ||
| }; | ||
| action.set(path$1, thr); | ||
| return thr; | ||
| } | ||
| _incrReadyCount() { | ||
| return this._readyCount++; | ||
| } | ||
| /** | ||
| * Awaits write operation to finish. | ||
| * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. | ||
| * @param path being acted upon | ||
| * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished | ||
| * @param event | ||
| * @param awfEmit Callback to be called when ready for event to be emitted. | ||
| */ | ||
| _awaitWriteFinish(path$1, threshold, event, awfEmit) { | ||
| const awf = this.options.awaitWriteFinish; | ||
| if (typeof awf !== "object") return; | ||
| const pollInterval = awf.pollInterval; | ||
| let timeoutHandler; | ||
| let fullPath = path$1; | ||
| if (this.options.cwd && !sp.isAbsolute(path$1)) fullPath = sp.join(this.options.cwd, path$1); | ||
| const now = /* @__PURE__ */ new Date(); | ||
| const writes = this._pendingWrites; | ||
| function awaitWriteFinishFn(prevStat) { | ||
| stat(fullPath, (err, curStat) => { | ||
| if (err || !writes.has(path$1)) { | ||
| if (err && err.code !== "ENOENT") awfEmit(err); | ||
| return; | ||
| } | ||
| const now$1 = Number(/* @__PURE__ */ new Date()); | ||
| if (prevStat && curStat.size !== prevStat.size) writes.get(path$1).lastChange = now$1; | ||
| if (now$1 - writes.get(path$1).lastChange >= threshold) { | ||
| writes.delete(path$1); | ||
| awfEmit(void 0, curStat); | ||
| } else timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat); | ||
| }); | ||
| } | ||
| if (!writes.has(path$1)) { | ||
| writes.set(path$1, { | ||
| lastChange: now, | ||
| cancelWait: () => { | ||
| writes.delete(path$1); | ||
| clearTimeout(timeoutHandler); | ||
| return event; | ||
| } | ||
| }); | ||
| timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval); | ||
| } | ||
| } | ||
| /** | ||
| * Determines whether user has asked to ignore this path. | ||
| */ | ||
| _isIgnored(path$1, stats) { | ||
| if (this.options.atomic && DOT_RE.test(path$1)) return true; | ||
| if (!this._userIgnored) { | ||
| const { cwd } = this.options; | ||
| const ignored = (this.options.ignored || []).map(normalizeIgnored(cwd)); | ||
| this._userIgnored = anymatch([...[...this._ignoredPaths].map(normalizeIgnored(cwd)), ...ignored], void 0); | ||
| } | ||
| return this._userIgnored(path$1, stats); | ||
| } | ||
| _isntIgnored(path$1, stat$2) { | ||
| return !this._isIgnored(path$1, stat$2); | ||
| } | ||
| /** | ||
| * Provides a set of common helpers and properties relating to symlink handling. | ||
| * @param path file or directory pattern being watched | ||
| */ | ||
| _getWatchHelpers(path$1) { | ||
| return new WatchHelper(path$1, this.options.followSymlinks, this); | ||
| } | ||
| /** | ||
| * Provides directory tracking objects | ||
| * @param directory path of the directory | ||
| */ | ||
| _getWatchedDir(directory) { | ||
| const dir = sp.resolve(directory); | ||
| if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove)); | ||
| return this._watched.get(dir); | ||
| } | ||
| /** | ||
| * Check for read permissions: https://stackoverflow.com/a/11781404/1358405 | ||
| */ | ||
| _hasReadPermissions(stats) { | ||
| if (this.options.ignorePermissionErrors) return true; | ||
| return Boolean(Number(stats.mode) & 256); | ||
| } | ||
| /** | ||
| * Handles emitting unlink events for | ||
| * files and directories, and via recursion, for | ||
| * files and directories within directories that are unlinked | ||
| * @param directory within which the following item is located | ||
| * @param item base path of item/directory | ||
| */ | ||
| _remove(directory, item, isDirectory) { | ||
| const path$1 = sp.join(directory, item); | ||
| const fullPath = sp.resolve(path$1); | ||
| isDirectory = isDirectory != null ? isDirectory : this._watched.has(path$1) || this._watched.has(fullPath); | ||
| if (!this._throttle("remove", path$1, 100)) return; | ||
| if (!isDirectory && this._watched.size === 1) this.add(directory, item, true); | ||
| this._getWatchedDir(path$1).getChildren().forEach((nested) => this._remove(path$1, nested)); | ||
| const parent = this._getWatchedDir(directory); | ||
| const wasTracked = parent.has(item); | ||
| parent.remove(item); | ||
| if (this._symlinkPaths.has(fullPath)) this._symlinkPaths.delete(fullPath); | ||
| let relPath = path$1; | ||
| if (this.options.cwd) relPath = sp.relative(this.options.cwd, path$1); | ||
| if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { | ||
| if (this._pendingWrites.get(relPath).cancelWait() === EVENTS.ADD) return; | ||
| } | ||
| this._watched.delete(path$1); | ||
| this._watched.delete(fullPath); | ||
| const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK; | ||
| if (wasTracked && !this._isIgnored(path$1)) this._emit(eventName, path$1); | ||
| this._closePath(path$1); | ||
| } | ||
| /** | ||
| * Closes all watchers for a path | ||
| */ | ||
| _closePath(path$1) { | ||
| this._closeFile(path$1); | ||
| const dir = sp.dirname(path$1); | ||
| this._getWatchedDir(dir).remove(sp.basename(path$1)); | ||
| } | ||
| /** | ||
| * Closes only file-specific watchers | ||
| */ | ||
| _closeFile(path$1) { | ||
| const closers = this._closers.get(path$1); | ||
| if (!closers) return; | ||
| closers.forEach((closer) => closer()); | ||
| this._closers.delete(path$1); | ||
| } | ||
| _addPathCloser(path$1, closer) { | ||
| if (!closer) return; | ||
| let list = this._closers.get(path$1); | ||
| if (!list) { | ||
| list = []; | ||
| this._closers.set(path$1, list); | ||
| } | ||
| list.push(closer); | ||
| } | ||
| _readdirp(root, opts) { | ||
| if (this.closed) return; | ||
| let stream = readdirp(root, { | ||
| type: EVENTS.ALL, | ||
| alwaysStat: true, | ||
| lstat: true, | ||
| ...opts, | ||
| depth: 0 | ||
| }); | ||
| this._streams.add(stream); | ||
| stream.once(STR_CLOSE, () => { | ||
| stream = void 0; | ||
| }); | ||
| stream.once(STR_END, () => { | ||
| if (stream) { | ||
| this._streams.delete(stream); | ||
| stream = void 0; | ||
| } | ||
| }); | ||
| return stream; | ||
| } | ||
| }; | ||
| /** | ||
| * Instantiates watcher with paths to be tracked. | ||
| * @param paths file / directory paths | ||
| * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others | ||
| * @returns an instance of FSWatcher for chaining. | ||
| * @example | ||
| * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); }); | ||
| * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') }) | ||
| */ | ||
| function watch$1(paths, options = {}) { | ||
| const watcher = new FSWatcher(options); | ||
| watcher.add(paths); | ||
| return watcher; | ||
| } | ||
| var chokidar_default = { | ||
| watch: watch$1, | ||
| FSWatcher | ||
| }; | ||
| //#endregion | ||
| export { watch$1 as n, chokidar_exports as t }; |
| import { C as decode, w as encode } from "../_build/common.mjs"; | ||
| //#region node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs | ||
| const schemeRegex = /^[\w+.-]+:\/\//; | ||
| /** | ||
| * Matches the parts of a URL: | ||
| * 1. Scheme, including ":", guaranteed. | ||
| * 2. User/password, including "@", optional. | ||
| * 3. Host, guaranteed. | ||
| * 4. Port, including ":", optional. | ||
| * 5. Path, including "/", optional. | ||
| * 6. Query, including "?", optional. | ||
| * 7. Hash, including "#", optional. | ||
| */ | ||
| const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; | ||
| /** | ||
| * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start | ||
| * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). | ||
| * | ||
| * 1. Host, optional. | ||
| * 2. Path, which may include "/", guaranteed. | ||
| * 3. Query, including "?", optional. | ||
| * 4. Hash, including "#", optional. | ||
| */ | ||
| const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; | ||
| function isAbsoluteUrl(input) { | ||
| return schemeRegex.test(input); | ||
| } | ||
| function isSchemeRelativeUrl(input) { | ||
| return input.startsWith("//"); | ||
| } | ||
| function isAbsolutePath(input) { | ||
| return input.startsWith("/"); | ||
| } | ||
| function isFileUrl(input) { | ||
| return input.startsWith("file:"); | ||
| } | ||
| function isRelative(input) { | ||
| return /^[.?#]/.test(input); | ||
| } | ||
| function parseAbsoluteUrl(input) { | ||
| const match = urlRegex.exec(input); | ||
| return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || ""); | ||
| } | ||
| function parseFileUrl(input) { | ||
| const match = fileRegex.exec(input); | ||
| const path = match[2]; | ||
| return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || ""); | ||
| } | ||
| function makeUrl(scheme, user, host, port, path, query, hash) { | ||
| return { | ||
| scheme, | ||
| user, | ||
| host, | ||
| port, | ||
| path, | ||
| query, | ||
| hash, | ||
| type: 7 | ||
| }; | ||
| } | ||
| function parseUrl(input) { | ||
| if (isSchemeRelativeUrl(input)) { | ||
| const url$1 = parseAbsoluteUrl("http:" + input); | ||
| url$1.scheme = ""; | ||
| url$1.type = 6; | ||
| return url$1; | ||
| } | ||
| if (isAbsolutePath(input)) { | ||
| const url$1 = parseAbsoluteUrl("http://foo.com" + input); | ||
| url$1.scheme = ""; | ||
| url$1.host = ""; | ||
| url$1.type = 5; | ||
| return url$1; | ||
| } | ||
| if (isFileUrl(input)) return parseFileUrl(input); | ||
| if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input); | ||
| const url = parseAbsoluteUrl("http://foo.com/" + input); | ||
| url.scheme = ""; | ||
| url.host = ""; | ||
| url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1; | ||
| return url; | ||
| } | ||
| function stripPathFilename(path) { | ||
| if (path.endsWith("/..")) return path; | ||
| const index = path.lastIndexOf("/"); | ||
| return path.slice(0, index + 1); | ||
| } | ||
| function mergePaths(url, base) { | ||
| normalizePath(base, base.type); | ||
| if (url.path === "/") url.path = base.path; | ||
| else url.path = stripPathFilename(base.path) + url.path; | ||
| } | ||
| /** | ||
| * The path can have empty directories "//", unneeded parents "foo/..", or current directory | ||
| * "foo/.". We need to normalize to a standard representation. | ||
| */ | ||
| function normalizePath(url, type) { | ||
| const rel = type <= 4; | ||
| const pieces = url.path.split("/"); | ||
| let pointer = 1; | ||
| let positive = 0; | ||
| let addTrailingSlash = false; | ||
| for (let i = 1; i < pieces.length; i++) { | ||
| const piece = pieces[i]; | ||
| if (!piece) { | ||
| addTrailingSlash = true; | ||
| continue; | ||
| } | ||
| addTrailingSlash = false; | ||
| if (piece === ".") continue; | ||
| if (piece === "..") { | ||
| if (positive) { | ||
| addTrailingSlash = true; | ||
| positive--; | ||
| pointer--; | ||
| } else if (rel) pieces[pointer++] = piece; | ||
| continue; | ||
| } | ||
| pieces[pointer++] = piece; | ||
| positive++; | ||
| } | ||
| let path = ""; | ||
| for (let i = 1; i < pointer; i++) path += "/" + pieces[i]; | ||
| if (!path || addTrailingSlash && !path.endsWith("/..")) path += "/"; | ||
| url.path = path; | ||
| } | ||
| /** | ||
| * Attempts to resolve `input` URL/path relative to `base`. | ||
| */ | ||
| function resolve(input, base) { | ||
| if (!input && !base) return ""; | ||
| const url = parseUrl(input); | ||
| let inputType = url.type; | ||
| if (base && inputType !== 7) { | ||
| const baseUrl = parseUrl(base); | ||
| const baseType = baseUrl.type; | ||
| switch (inputType) { | ||
| case 1: url.hash = baseUrl.hash; | ||
| case 2: url.query = baseUrl.query; | ||
| case 3: | ||
| case 4: mergePaths(url, baseUrl); | ||
| case 5: | ||
| url.user = baseUrl.user; | ||
| url.host = baseUrl.host; | ||
| url.port = baseUrl.port; | ||
| case 6: url.scheme = baseUrl.scheme; | ||
| } | ||
| if (baseType > inputType) inputType = baseType; | ||
| } | ||
| normalizePath(url, inputType); | ||
| const queryHash = url.query + url.hash; | ||
| switch (inputType) { | ||
| case 2: | ||
| case 3: return queryHash; | ||
| case 4: { | ||
| const path = url.path.slice(1); | ||
| if (!path) return queryHash || "."; | ||
| if (isRelative(base || input) && !isRelative(path)) return "./" + path + queryHash; | ||
| return path + queryHash; | ||
| } | ||
| case 5: return url.path + queryHash; | ||
| default: return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash; | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs | ||
| function stripFilename(path) { | ||
| if (!path) return ""; | ||
| const index = path.lastIndexOf("/"); | ||
| return path.slice(0, index + 1); | ||
| } | ||
| function resolver(mapUrl, sourceRoot) { | ||
| const from = stripFilename(mapUrl); | ||
| const prefix = sourceRoot ? sourceRoot + "/" : ""; | ||
| return (source) => resolve(prefix + (source || ""), from); | ||
| } | ||
| var COLUMN$1 = 0; | ||
| function maybeSort(mappings, owned) { | ||
| const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); | ||
| if (unsortedIndex === mappings.length) return mappings; | ||
| if (!owned) mappings = mappings.slice(); | ||
| for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) mappings[i] = sortSegments(mappings[i], owned); | ||
| return mappings; | ||
| } | ||
| function nextUnsortedSegmentLine(mappings, start) { | ||
| for (let i = start; i < mappings.length; i++) if (!isSorted(mappings[i])) return i; | ||
| return mappings.length; | ||
| } | ||
| function isSorted(line) { | ||
| for (let j = 1; j < line.length; j++) if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) return false; | ||
| return true; | ||
| } | ||
| function sortSegments(line, owned) { | ||
| if (!owned) line = line.slice(); | ||
| return line.sort(sortComparator); | ||
| } | ||
| function sortComparator(a, b) { | ||
| return a[COLUMN$1] - b[COLUMN$1]; | ||
| } | ||
| var found = false; | ||
| function binarySearch(haystack, needle, low, high) { | ||
| while (low <= high) { | ||
| const mid = low + (high - low >> 1); | ||
| const cmp = haystack[mid][COLUMN$1] - needle; | ||
| if (cmp === 0) { | ||
| found = true; | ||
| return mid; | ||
| } | ||
| if (cmp < 0) low = mid + 1; | ||
| else high = mid - 1; | ||
| } | ||
| found = false; | ||
| return low - 1; | ||
| } | ||
| function upperBound(haystack, needle, index) { | ||
| for (let i = index + 1; i < haystack.length; index = i++) if (haystack[i][COLUMN$1] !== needle) break; | ||
| return index; | ||
| } | ||
| function lowerBound(haystack, needle, index) { | ||
| for (let i = index - 1; i >= 0; index = i--) if (haystack[i][COLUMN$1] !== needle) break; | ||
| return index; | ||
| } | ||
| function memoizedState() { | ||
| return { | ||
| lastKey: -1, | ||
| lastNeedle: -1, | ||
| lastIndex: -1 | ||
| }; | ||
| } | ||
| function memoizedBinarySearch(haystack, needle, state, key) { | ||
| const { lastKey, lastNeedle, lastIndex } = state; | ||
| let low = 0; | ||
| let high = haystack.length - 1; | ||
| if (key === lastKey) { | ||
| if (needle === lastNeedle) { | ||
| found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle; | ||
| return lastIndex; | ||
| } | ||
| if (needle >= lastNeedle) low = lastIndex === -1 ? 0 : lastIndex; | ||
| else high = lastIndex; | ||
| } | ||
| state.lastKey = key; | ||
| state.lastNeedle = needle; | ||
| return state.lastIndex = binarySearch(haystack, needle, low, high); | ||
| } | ||
| function parse(map) { | ||
| return typeof map === "string" ? JSON.parse(map) : map; | ||
| } | ||
| var LEAST_UPPER_BOUND = -1; | ||
| var GREATEST_LOWER_BOUND = 1; | ||
| var TraceMap = class { | ||
| constructor(map, mapUrl) { | ||
| const isString = typeof map === "string"; | ||
| if (!isString && map._decodedMemo) return map; | ||
| const parsed = parse(map); | ||
| const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; | ||
| this.version = version; | ||
| this.file = file; | ||
| this.names = names || []; | ||
| this.sourceRoot = sourceRoot; | ||
| this.sources = sources; | ||
| this.sourcesContent = sourcesContent; | ||
| this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0; | ||
| const resolve$1 = resolver(mapUrl, sourceRoot); | ||
| this.resolvedSources = sources.map(resolve$1); | ||
| const { mappings } = parsed; | ||
| if (typeof mappings === "string") { | ||
| this._encoded = mappings; | ||
| this._decoded = void 0; | ||
| } else if (Array.isArray(mappings)) { | ||
| this._encoded = void 0; | ||
| this._decoded = maybeSort(mappings, isString); | ||
| } else if (parsed.sections) throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`); | ||
| else throw new Error(`invalid source map: ${JSON.stringify(parsed)}`); | ||
| this._decodedMemo = memoizedState(); | ||
| this._bySources = void 0; | ||
| this._bySourceMemos = void 0; | ||
| } | ||
| }; | ||
| function cast$1(map) { | ||
| return map; | ||
| } | ||
| function decodedMappings(map) { | ||
| var _a; | ||
| return (_a = cast$1(map))._decoded || (_a._decoded = decode(cast$1(map)._encoded)); | ||
| } | ||
| function traceSegment(map, line, column) { | ||
| const decoded = decodedMappings(map); | ||
| if (line >= decoded.length) return null; | ||
| const segments = decoded[line]; | ||
| const index = traceSegmentInternal(segments, cast$1(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND); | ||
| return index === -1 ? null : segments[index]; | ||
| } | ||
| function traceSegmentInternal(segments, memo, line, column, bias) { | ||
| let index = memoizedBinarySearch(segments, column, memo, line); | ||
| if (found) index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); | ||
| else if (bias === LEAST_UPPER_BOUND) index++; | ||
| if (index === -1 || index === segments.length) return -1; | ||
| return index; | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs | ||
| var SetArray = class { | ||
| constructor() { | ||
| this._indexes = { __proto__: null }; | ||
| this.array = []; | ||
| } | ||
| }; | ||
| function cast(set) { | ||
| return set; | ||
| } | ||
| function get(setarr, key) { | ||
| return cast(setarr)._indexes[key]; | ||
| } | ||
| function put(setarr, key) { | ||
| const index = get(setarr, key); | ||
| if (index !== void 0) return index; | ||
| const { array, _indexes: indexes } = cast(setarr); | ||
| return indexes[key] = array.push(key) - 1; | ||
| } | ||
| function remove(setarr, key) { | ||
| const index = get(setarr, key); | ||
| if (index === void 0) return; | ||
| const { array, _indexes: indexes } = cast(setarr); | ||
| for (let i = index + 1; i < array.length; i++) { | ||
| const k = array[i]; | ||
| array[i - 1] = k; | ||
| indexes[k]--; | ||
| } | ||
| indexes[key] = void 0; | ||
| array.pop(); | ||
| } | ||
| var COLUMN = 0; | ||
| var SOURCES_INDEX = 1; | ||
| var SOURCE_LINE = 2; | ||
| var SOURCE_COLUMN = 3; | ||
| var NAMES_INDEX = 4; | ||
| var NO_NAME = -1; | ||
| var GenMapping = class { | ||
| constructor({ file, sourceRoot } = {}) { | ||
| this._names = new SetArray(); | ||
| this._sources = new SetArray(); | ||
| this._sourcesContent = []; | ||
| this._mappings = []; | ||
| this.file = file; | ||
| this.sourceRoot = sourceRoot; | ||
| this._ignoreList = new SetArray(); | ||
| } | ||
| }; | ||
| function cast2(map) { | ||
| return map; | ||
| } | ||
| var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { | ||
| return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); | ||
| }; | ||
| function setSourceContent(map, source, content) { | ||
| const { _sources: sources, _sourcesContent: sourcesContent } = cast2(map); | ||
| const index = put(sources, source); | ||
| sourcesContent[index] = content; | ||
| } | ||
| function setIgnore(map, source, ignore = true) { | ||
| const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast2(map); | ||
| const index = put(sources, source); | ||
| if (index === sourcesContent.length) sourcesContent[index] = null; | ||
| if (ignore) put(ignoreList, index); | ||
| else remove(ignoreList, index); | ||
| } | ||
| function toDecodedMap(map) { | ||
| const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast2(map); | ||
| removeEmptyFinalLines(mappings); | ||
| return { | ||
| version: 3, | ||
| file: map.file || void 0, | ||
| names: names.array, | ||
| sourceRoot: map.sourceRoot || void 0, | ||
| sources: sources.array, | ||
| sourcesContent, | ||
| mappings, | ||
| ignoreList: ignoreList.array | ||
| }; | ||
| } | ||
| function toEncodedMap(map) { | ||
| const decoded = toDecodedMap(map); | ||
| return Object.assign({}, decoded, { mappings: encode(decoded.mappings) }); | ||
| } | ||
| function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { | ||
| const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast2(map); | ||
| const line = getIndex(mappings, genLine); | ||
| const index = getColumnIndex(line, genColumn); | ||
| if (!source) { | ||
| if (skipable && skipSourceless(line, index)) return; | ||
| return insert(line, index, [genColumn]); | ||
| } | ||
| assert(sourceLine); | ||
| assert(sourceColumn); | ||
| const sourcesIndex = put(sources, source); | ||
| const namesIndex = name ? put(names, name) : NO_NAME; | ||
| if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null; | ||
| if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) return; | ||
| return insert(line, index, name ? [ | ||
| genColumn, | ||
| sourcesIndex, | ||
| sourceLine, | ||
| sourceColumn, | ||
| namesIndex | ||
| ] : [ | ||
| genColumn, | ||
| sourcesIndex, | ||
| sourceLine, | ||
| sourceColumn | ||
| ]); | ||
| } | ||
| function assert(_val) {} | ||
| function getIndex(arr, index) { | ||
| for (let i = arr.length; i <= index; i++) arr[i] = []; | ||
| return arr[index]; | ||
| } | ||
| function getColumnIndex(line, genColumn) { | ||
| let index = line.length; | ||
| for (let i = index - 1; i >= 0; index = i--) if (genColumn >= line[i][COLUMN]) break; | ||
| return index; | ||
| } | ||
| function insert(array, index, value) { | ||
| for (let i = array.length; i > index; i--) array[i] = array[i - 1]; | ||
| array[index] = value; | ||
| } | ||
| function removeEmptyFinalLines(mappings) { | ||
| const { length } = mappings; | ||
| let len = length; | ||
| for (let i = len - 1; i >= 0; len = i, i--) if (mappings[i].length > 0) break; | ||
| if (len < length) mappings.length = len; | ||
| } | ||
| function skipSourceless(line, index) { | ||
| if (index === 0) return true; | ||
| return line[index - 1].length === 1; | ||
| } | ||
| function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { | ||
| if (index === 0) return false; | ||
| const prev = line[index - 1]; | ||
| if (prev.length === 1) return false; | ||
| return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME); | ||
| } | ||
| //#endregion | ||
| export { toDecodedMap as a, decodedMappings as c, setSourceContent as i, traceSegment as l, maybeAddSegment as n, toEncodedMap as o, setIgnore as r, TraceMap as s, GenMapping as t }; |
| //#region node_modules/.pnpm/rou3@0.7.12/node_modules/rou3/dist/index.d.mts | ||
| interface RouterContext<T = unknown> { | ||
| root: Node<T>; | ||
| static: Record<string, Node<T> | undefined>; | ||
| } | ||
| type ParamsIndexMap = Array<[Index: number, name: string | RegExp, optional: boolean]>; | ||
| type MethodData<T = unknown> = { | ||
| data: T; | ||
| paramsMap?: ParamsIndexMap; | ||
| paramsRegexp: RegExp[]; | ||
| }; | ||
| interface Node<T = unknown> { | ||
| key: string; | ||
| static?: Record<string, Node<T>>; | ||
| param?: Node<T>; | ||
| wildcard?: Node<T>; | ||
| hasRegexParam?: boolean; | ||
| methods?: Record<string, MethodData<T>[] | undefined>; | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/rou3@0.7.12/node_modules/rou3/dist/compiler.d.mts | ||
| interface RouterCompilerOptions<T = any> { | ||
| matchAll?: boolean; | ||
| serialize?: (data: T) => string; | ||
| } | ||
| /** | ||
| * Compiles the router instance into a faster route-matching function. | ||
| * | ||
| * **IMPORTANT:** `compileRouter` requires eval support with `new Function()` in the runtime for JIT compilation. | ||
| * | ||
| * @example | ||
| * import { createRouter, addRoute } from "rou3"; | ||
| * import { compileRouter } from "rou3/compiler"; | ||
| * const router = createRouter(); | ||
| * // [add some routes] | ||
| * const findRoute = compileRouter(router); | ||
| * const matchAll = compileRouter(router, { matchAll: true }); | ||
| * findRoute("GET", "/path/foo/bar"); | ||
| * | ||
| * @param router - The router context to compile. | ||
| */ | ||
| //#endregion | ||
| export { RouterContext as n, RouterCompilerOptions as t }; |
| //#region node_modules/.pnpm/std-env@3.10.0/node_modules/std-env/dist/index.d.ts | ||
| type ProviderName = "" | "appveyor" | "aws_amplify" | "azure_pipelines" | "azure_static" | "appcircle" | "bamboo" | "bitbucket" | "bitrise" | "buddy" | "buildkite" | "circle" | "cirrus" | "cloudflare_pages" | "cloudflare_workers" | "codebuild" | "codefresh" | "drone" | "drone" | "dsari" | "github_actions" | "gitlab" | "gocd" | "layerci" | "hudson" | "jenkins" | "magnum" | "netlify" | "nevercode" | "render" | "sail" | "semaphore" | "screwdriver" | "shippable" | "solano" | "strider" | "teamcity" | "travis" | "vercel" | "appcenter" | "codesandbox" | "stackblitz" | "stormkit" | "cleavr" | "zeabur" | "codesphere" | "railway" | "deno-deploy" | "firebase_app_hosting"; | ||
| //#endregion | ||
| export { ProviderName as t }; |
Sorry, the diff of this file is too big to display
| import { t as MagicString } from "./magic-string.mjs"; | ||
| import { t as ESMExport } from "./mlly.mjs"; | ||
| import "vite"; | ||
| import "rolldown"; | ||
| import "rollup"; | ||
| import "webpack"; | ||
| import "@farmfe/core"; | ||
| import "@rspack/core"; | ||
| import "unloader"; | ||
| //#region node_modules/.pnpm/unplugin-utils@0.3.1/node_modules/unplugin-utils/dist/index.d.ts | ||
| //#region src/filter.d.ts | ||
| /** | ||
| * A valid `picomatch` glob pattern, or array of patterns. | ||
| */ | ||
| type FilterPattern = ReadonlyArray<string | RegExp> | string | RegExp | null; | ||
| /** | ||
| * Constructs a filter function which can be used to determine whether or not | ||
| * certain modules should be operated upon. | ||
| * @param include If `include` is omitted or has zero length, filter will return `true` by default. | ||
| * @param exclude ID must not match any of the `exclude` patterns. | ||
| * @param options Additional options. | ||
| * @param options.resolve Optionally resolves the patterns against a directory other than `process.cwd()`. | ||
| * If a `string` is specified, then the value will be used as the base directory. | ||
| * Relative paths will be resolved against `process.cwd()` first. | ||
| * If `false`, then the patterns will not be resolved against any directory. | ||
| * This can be useful if you want to create a filter for virtual module names. | ||
| */ | ||
| //#endregion | ||
| //#region node_modules/.pnpm/unimport@5.6.0/node_modules/unimport/dist/shared/unimport.C0UbTDPO.d.mts | ||
| declare const builtinPresets: { | ||
| '@vue/composition-api': InlinePreset; | ||
| '@vueuse/core': () => Preset; | ||
| '@vueuse/head': InlinePreset; | ||
| pinia: InlinePreset; | ||
| preact: InlinePreset; | ||
| quasar: InlinePreset; | ||
| react: InlinePreset; | ||
| 'react-router': InlinePreset; | ||
| 'react-router-dom': InlinePreset; | ||
| svelte: InlinePreset; | ||
| 'svelte/animate': InlinePreset; | ||
| 'svelte/easing': InlinePreset; | ||
| 'svelte/motion': InlinePreset; | ||
| 'svelte/store': InlinePreset; | ||
| 'svelte/transition': InlinePreset; | ||
| 'vee-validate': InlinePreset; | ||
| vitepress: InlinePreset; | ||
| 'vue-demi': InlinePreset; | ||
| 'vue-i18n': InlinePreset; | ||
| 'vue-router': InlinePreset; | ||
| 'vue-router-composables': InlinePreset; | ||
| vue: InlinePreset; | ||
| 'vue/macros': InlinePreset; | ||
| vuex: InlinePreset; | ||
| vitest: InlinePreset; | ||
| 'uni-app': InlinePreset; | ||
| 'solid-js': InlinePreset; | ||
| 'solid-app-router': InlinePreset; | ||
| rxjs: InlinePreset; | ||
| 'date-fns': InlinePreset; | ||
| }; | ||
| type BuiltinPresetName = keyof typeof builtinPresets; | ||
| type ModuleId = string; | ||
| type ImportName = string; | ||
| interface ImportCommon { | ||
| /** Module specifier to import from */ | ||
| from: ModuleId; | ||
| /** | ||
| * Priority of the import, if multiple imports have the same name, the one with the highest priority will be used | ||
| * @default 1 | ||
| */ | ||
| priority?: number; | ||
| /** If this import is disabled */ | ||
| disabled?: boolean; | ||
| /** Won't output import in declaration file if true */ | ||
| dtsDisabled?: boolean; | ||
| /** Import declaration type like const / var / enum */ | ||
| declarationType?: ESMExport['declarationType']; | ||
| /** | ||
| * Metadata of the import | ||
| */ | ||
| meta?: { | ||
| /** Short description of the import */description?: string; /** URL to the documentation */ | ||
| docsUrl?: string; /** Additional metadata */ | ||
| [key: string]: any; | ||
| }; | ||
| /** | ||
| * If this import is a pure type import | ||
| */ | ||
| type?: boolean; | ||
| /** | ||
| * Using this as the from when generating type declarations | ||
| */ | ||
| typeFrom?: ModuleId; | ||
| } | ||
| interface Import extends ImportCommon { | ||
| /** Import name to be detected */ | ||
| name: ImportName; | ||
| /** Import as this name */ | ||
| as?: ImportName; | ||
| /** | ||
| * With properties | ||
| * | ||
| * Ignored for CJS imports. | ||
| */ | ||
| with?: Record<string, string>; | ||
| } | ||
| type PresetImport = Omit<Import, 'from'> | ImportName | [name: ImportName, as?: ImportName, from?: ModuleId]; | ||
| interface InlinePreset extends ImportCommon { | ||
| imports: (PresetImport | InlinePreset)[]; | ||
| } | ||
| /** | ||
| * Auto extract exports from a package for auto import | ||
| */ | ||
| interface PackagePreset { | ||
| /** | ||
| * Name of the package | ||
| */ | ||
| package: string; | ||
| /** | ||
| * Path of the importer | ||
| * @default process.cwd() | ||
| */ | ||
| url?: string; | ||
| /** | ||
| * RegExp, string, or custom function to exclude names of the extracted imports | ||
| */ | ||
| ignore?: (string | RegExp | ((name: string) => boolean))[]; | ||
| /** | ||
| * Use local cache if exits | ||
| * @default true | ||
| */ | ||
| cache?: boolean; | ||
| } | ||
| type Preset = InlinePreset | PackagePreset; | ||
| interface UnimportContext { | ||
| readonly version: string; | ||
| options: Partial<UnimportOptions>; | ||
| staticImports: Import[]; | ||
| dynamicImports: Import[]; | ||
| addons: Addon[]; | ||
| getImports: () => Promise<Import[]>; | ||
| getImportMap: () => Promise<Map<string, Import>>; | ||
| getMetadata: () => UnimportMeta | undefined; | ||
| modifyDynamicImports: (fn: (imports: Import[]) => Thenable<void | Import[]>) => Promise<void>; | ||
| clearDynamicImports: () => void; | ||
| replaceImports: (imports: UnimportOptions['imports']) => Promise<Import[]>; | ||
| invalidate: () => void; | ||
| resolveId: (id: string, parentId?: string) => Thenable<string | null | undefined | void>; | ||
| } | ||
| interface DetectImportResult { | ||
| s: MagicString; | ||
| strippedCode: string; | ||
| isCJSContext: boolean; | ||
| matchedImports: Import[]; | ||
| firstOccurrence: number; | ||
| } | ||
| interface Unimport { | ||
| readonly version: string; | ||
| init: () => Promise<void>; | ||
| clearDynamicImports: UnimportContext['clearDynamicImports']; | ||
| getImportMap: UnimportContext['getImportMap']; | ||
| getImports: UnimportContext['getImports']; | ||
| getInternalContext: () => UnimportContext; | ||
| getMetadata: UnimportContext['getMetadata']; | ||
| modifyDynamicImports: UnimportContext['modifyDynamicImports']; | ||
| generateTypeDeclarations: (options?: TypeDeclarationOptions) => Promise<string>; | ||
| /** | ||
| * Get un-imported usages from code | ||
| */ | ||
| detectImports: (code: string | MagicString) => Promise<DetectImportResult>; | ||
| /** | ||
| * Insert missing imports statements to code | ||
| */ | ||
| injectImports: (code: string | MagicString, id?: string, options?: InjectImportsOptions) => Promise<ImportInjectionResult>; | ||
| scanImportsFromDir: (dir?: (string | ScanDir)[], options?: ScanDirExportsOptions) => Promise<Import[]>; | ||
| scanImportsFromFile: (file: string, includeTypes?: boolean) => Promise<Import[]>; | ||
| /** | ||
| * @deprecated | ||
| */ | ||
| toExports: (filepath?: string, includeTypes?: boolean) => Promise<string>; | ||
| } | ||
| interface InjectionUsageRecord { | ||
| import: Import; | ||
| count: number; | ||
| moduleIds: string[]; | ||
| } | ||
| interface UnimportMeta { | ||
| injectionUsage: Record<string, InjectionUsageRecord>; | ||
| } | ||
| interface AddonsOptions { | ||
| addons?: Addon[]; | ||
| /** | ||
| * Enable auto import inside for Vue's <template> | ||
| * | ||
| * @default false | ||
| */ | ||
| vueTemplate?: boolean; | ||
| /** | ||
| * Enable auto import directives for Vue's SFC. | ||
| * | ||
| * Library authors should include `meta.vueDirective: true` in the import metadata. | ||
| * | ||
| * When using a local directives folder, provide the `isDirective` | ||
| * callback to check if the import is a Vue directive. | ||
| */ | ||
| vueDirectives?: true | AddonVueDirectivesOptions; | ||
| } | ||
| interface AddonVueDirectivesOptions { | ||
| /** | ||
| * Checks if the import is a Vue directive. | ||
| * | ||
| * **NOTES**: | ||
| * - imports from a library should include `meta.vueDirective: true`. | ||
| * - this callback is only invoked for local directives (only when meta.vueDirective is not set). | ||
| * | ||
| * @param from The path of the import normalized. | ||
| * @param importEntry The import entry. | ||
| */ | ||
| isDirective?: (from: string, importEntry: Import) => boolean; | ||
| } | ||
| interface UnimportOptions extends Pick<InjectImportsOptions, 'injectAtEnd' | 'mergeExisting' | 'parser'> { | ||
| /** | ||
| * Auto import items | ||
| */ | ||
| imports: Import[]; | ||
| /** | ||
| * Auto import preset | ||
| */ | ||
| presets: (Preset | BuiltinPresetName)[]; | ||
| /** | ||
| * Custom warning function | ||
| * @default console.warn | ||
| */ | ||
| warn: (msg: string) => void; | ||
| /** | ||
| * Custom debug log function | ||
| * @default console.log | ||
| */ | ||
| debugLog: (msg: string) => void; | ||
| /** | ||
| * Unimport Addons. | ||
| * To use built-in addons, use: | ||
| * ```js | ||
| * addons: { | ||
| * addons: [<custom-addons-here>] // if you want to use also custom addons | ||
| * vueTemplate: true, | ||
| * vueDirectives: [<the-directives-here>] | ||
| * } | ||
| * ``` | ||
| * | ||
| * Built-in addons: | ||
| * - vueDirectives: enable auto import directives for Vue's SFC | ||
| * - vueTemplate: enable auto import inside for Vue's <template> | ||
| * | ||
| * @default {} | ||
| */ | ||
| addons: AddonsOptions | Addon[]; | ||
| /** | ||
| * Name of virtual modules that exposed all the registed auto-imports | ||
| * @default [] | ||
| */ | ||
| virtualImports: string[]; | ||
| /** | ||
| * Directories to scan for auto import | ||
| * @default [] | ||
| */ | ||
| dirs?: (string | ScanDir)[]; | ||
| /** | ||
| * Options for scanning directories for auto import | ||
| */ | ||
| dirsScanOptions?: ScanDirExportsOptions; | ||
| /** | ||
| * Custom resolver to auto import id | ||
| */ | ||
| resolveId?: (id: string, importee?: string) => Thenable<string | void>; | ||
| /** | ||
| * Custom magic comments to be opt-out for auto import, per file/module | ||
| * | ||
| * @default ['@unimport-disable', '@imports-disable'] | ||
| */ | ||
| commentsDisable?: string[]; | ||
| /** | ||
| * Custom magic comments to debug auto import, printed to console | ||
| * | ||
| * @default ['@unimport-debug', '@imports-debug'] | ||
| */ | ||
| commentsDebug?: string[]; | ||
| /** | ||
| * Collect meta data for each auto import. Accessible via `ctx.meta` | ||
| */ | ||
| collectMeta?: boolean; | ||
| } | ||
| type PathFromResolver = (_import: Import) => string | undefined; | ||
| interface ScanDirExportsOptions { | ||
| /** | ||
| * Glob patterns for matching files | ||
| * | ||
| * @default ['*.{ts,js,mjs,cjs,mts,cts,tsx,jsx}'] | ||
| */ | ||
| filePatterns?: string[]; | ||
| /** | ||
| * Custom function to filter scanned files | ||
| */ | ||
| fileFilter?: (file: string) => boolean; | ||
| /** | ||
| * Register type exports | ||
| * | ||
| * @default true | ||
| */ | ||
| types?: boolean; | ||
| /** | ||
| * Current working directory | ||
| * | ||
| * @default process.cwd() | ||
| */ | ||
| cwd?: string; | ||
| } | ||
| interface ScanDir { | ||
| /** | ||
| * Path pattern of the directory | ||
| */ | ||
| glob: string; | ||
| /** | ||
| * Register type exports | ||
| * | ||
| * @default true | ||
| */ | ||
| types?: boolean; | ||
| } | ||
| interface TypeDeclarationOptions { | ||
| /** | ||
| * Custom resolver for path of the import | ||
| */ | ||
| resolvePath?: PathFromResolver; | ||
| /** | ||
| * Append `export {}` to the end of the file | ||
| * | ||
| * @default true | ||
| */ | ||
| exportHelper?: boolean; | ||
| /** | ||
| * Auto-import for type exports | ||
| * | ||
| * @default true | ||
| */ | ||
| typeReExports?: boolean; | ||
| } | ||
| interface InjectImportsOptions { | ||
| /** | ||
| * Merge the existing imports | ||
| * | ||
| * @default false | ||
| */ | ||
| mergeExisting?: boolean; | ||
| /** | ||
| * If the module should be auto imported | ||
| * | ||
| * @default true | ||
| */ | ||
| autoImport?: boolean; | ||
| /** | ||
| * If the module should be transformed for virtual modules. | ||
| * Only available when `virtualImports` is set. | ||
| * | ||
| * @default true | ||
| */ | ||
| transformVirtualImports?: boolean; | ||
| /** | ||
| * Parser to use for parsing the code | ||
| * | ||
| * Note that `acorn` only takes valid JS Code, should usually only be used after transformationa and transpilation | ||
| * | ||
| * @default 'regex' | ||
| */ | ||
| parser?: 'acorn' | 'regex'; | ||
| /** | ||
| * Inject the imports at the end of other imports | ||
| * | ||
| * @default false | ||
| */ | ||
| injectAtEnd?: boolean; | ||
| } | ||
| type Thenable<T> = Promise<T> | T; | ||
| interface Addon { | ||
| name?: string; | ||
| transform?: (this: UnimportContext, code: MagicString, id: string | undefined) => Thenable<MagicString>; | ||
| declaration?: (this: UnimportContext, dts: string, options: TypeDeclarationOptions) => Thenable<string>; | ||
| matchImports?: (this: UnimportContext, identifiers: Set<string>, matched: Import[]) => Thenable<Import[] | void>; | ||
| /** | ||
| * Extend or modify the imports list before injecting | ||
| */ | ||
| extendImports?: (this: UnimportContext, imports: Import[]) => Import[] | void; | ||
| /** | ||
| * Resolve imports before injecting | ||
| */ | ||
| injectImportsResolved?: (this: UnimportContext, imports: Import[], code: MagicString, id?: string) => Import[] | void; | ||
| /** | ||
| * Modify the injection code before injecting | ||
| */ | ||
| injectImportsStringified?: (this: UnimportContext, injection: string, imports: Import[], code: MagicString, id?: string) => string | void; | ||
| } | ||
| interface MagicStringResult { | ||
| s: MagicString; | ||
| code: string; | ||
| } | ||
| interface ImportInjectionResult extends MagicStringResult { | ||
| imports: Import[]; | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/unimport@5.6.0/node_modules/unimport/dist/unplugin.d.mts | ||
| interface UnimportPluginOptions extends UnimportOptions { | ||
| include: FilterPattern; | ||
| exclude: FilterPattern; | ||
| dts: boolean | string; | ||
| /** | ||
| * Enable implicit auto import. | ||
| * Generate global TypeScript definitions. | ||
| * | ||
| * @default true | ||
| */ | ||
| autoImport?: boolean; | ||
| } | ||
| //#endregion | ||
| export { type Unimport as n, type UnimportPluginOptions as t }; |
| import { Plugin } from "rollup"; | ||
| //#region node_modules/.pnpm/unwasm@0.5.3/node_modules/unwasm/dist/plugin/index.d.mts | ||
| //#region src/plugin/shared.d.ts | ||
| interface UnwasmPluginOptions { | ||
| /** | ||
| * Directly import the `.wasm` files instead of bundling as base64 string. | ||
| * | ||
| * @default false | ||
| */ | ||
| esmImport?: boolean; | ||
| /** | ||
| * Avoid using top level await and always use a proxy. | ||
| * | ||
| * Useful for compatibility with environments that don't support top level await. | ||
| * | ||
| * @default false | ||
| */ | ||
| lazy?: boolean; | ||
| /** | ||
| * Suppress all warnings from the plugin. | ||
| * | ||
| * @default false | ||
| */ | ||
| silent?: boolean; | ||
| } //#endregion | ||
| //#region src/plugin/index.d.ts | ||
| //#endregion | ||
| export { UnwasmPluginOptions as t }; |
| import { | ||
| colors, | ||
| stripAnsi | ||
| } from "./chunk-4L7RY2JA.js"; | ||
| import { | ||
| BaseComponent, | ||
| publicDirURL | ||
| } from "./chunk-PE3GG3TN.js"; | ||
| // src/templates/error_stack_source/main.ts | ||
| import { extname } from "path"; | ||
| import { highlightText } from "@speed-highlight/core"; | ||
| import { highlightText as cliHighlightText } from "@speed-highlight/core/terminal"; | ||
| var GUTTER = "\u2503"; | ||
| var POINTER = "\u276F"; | ||
| var LANGS_MAP = { | ||
| ".tsx": "ts", | ||
| ".jsx": "js", | ||
| ".js": "js", | ||
| ".ts": "ts", | ||
| ".css": "css", | ||
| ".json": "json", | ||
| ".html": "html", | ||
| ".astro": "ts", | ||
| ".vue": "ts" | ||
| }; | ||
| var ErrorStackSource = class extends BaseComponent { | ||
| cssFile = new URL("./error_stack_source/style.css", publicDirURL); | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML(props) { | ||
| const frame = props.frame; | ||
| if (frame.type === "native" || !frame.source || !frame.fileName) { | ||
| return ""; | ||
| } | ||
| const language = LANGS_MAP[extname(frame.fileName)] ?? "plain"; | ||
| const highlightMarginTop = `${frame.source.findIndex((chunk) => { | ||
| return chunk.lineNumber === frame.lineNumber; | ||
| }) * 24}px`; | ||
| const highlight = `<div class="line-highlight" style="margin-top: ${highlightMarginTop}"></div>`; | ||
| let code = await highlightText( | ||
| frame.source.map((chunk) => chunk.chunk).join("\n"), | ||
| language, | ||
| true | ||
| ); | ||
| code = code.replace( | ||
| '<div class="shj-numbers">', | ||
| `<div class="shj-numbers" style="counter-set: line ${frame.source[0].lineNumber - 1}">` | ||
| ); | ||
| return `<pre><code class="shj-lang-js">${highlight}${code}</code></pre>`; | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI(props) { | ||
| const frame = props.frame; | ||
| if (frame.type === "native" || !frame.source || !frame.fileName) { | ||
| return ""; | ||
| } | ||
| const language = LANGS_MAP[extname(frame.fileName)] ?? "plain"; | ||
| const largestLineNumber = Math.max(...frame.source.map(({ lineNumber }) => lineNumber)); | ||
| const lineNumberCols = String(largestLineNumber).length; | ||
| const code = frame.source.map(({ chunk }) => chunk).join("\n"); | ||
| const highlighted = await cliHighlightText(code, language); | ||
| return ` | ||
| ${highlighted.split("\n").map((line, index) => { | ||
| const lineNumber = frame.source[index].lineNumber; | ||
| const alignedLineNumber = String(lineNumber).padStart(lineNumberCols, " "); | ||
| if (lineNumber === props.frame.lineNumber) { | ||
| return ` ${colors.bgRed(`${POINTER} ${alignedLineNumber} ${GUTTER} ${stripAnsi(line)}`)}`; | ||
| } | ||
| return ` ${colors.dim(alignedLineNumber)} ${colors.dim(GUTTER)} ${line}`; | ||
| }).join("\n")} | ||
| `; | ||
| } | ||
| }; | ||
| export { | ||
| ErrorStackSource | ||
| }; |
| import { | ||
| BaseComponent, | ||
| publicDirURL | ||
| } from "./chunk-PE3GG3TN.js"; | ||
| // src/templates/header/main.ts | ||
| var DARK_MODE_SVG = `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M0 0h24v24H0z" stroke="none"/><path d="M12 3h.393a7.5 7.5 0 0 0 7.92 12.446A9 9 0 1 1 12 2.992z"/></svg>`; | ||
| var LIGHT_MODE_SVG = `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M0 0h24v24H0z" stroke="none"/><circle cx="12" cy="12" r="4"/><path d="M3 12h1m8-9v1m8 8h1m-9 8v1M5.6 5.6l.7.7m12.1-.7-.7.7m0 11.4.7.7m-12.1-.7-.7.7"/></svg>`; | ||
| var Header = class extends BaseComponent { | ||
| cssFile = new URL("./header/style.css", publicDirURL); | ||
| scriptFile = new URL("./header/script.js", publicDirURL); | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML() { | ||
| return `<header id="header"> | ||
| <div id="header-actions"> | ||
| <div id="toggle-theme-container"> | ||
| <input type="checkbox" id="toggle-theme-checkbox" /> | ||
| <label id="toggle-theme-label" for="toggle-theme-checkbox"> | ||
| <span id="light-theme-indicator" title="Light mode">${LIGHT_MODE_SVG}</span> | ||
| <span id="dark-theme-indicator" title="Dark mode">${DARK_MODE_SVG}</span> | ||
| </label> | ||
| </div> | ||
| </div> | ||
| </header>`; | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI() { | ||
| return ""; | ||
| } | ||
| }; | ||
| export { | ||
| Header | ||
| }; |
| import { | ||
| BaseComponent, | ||
| publicDirURL | ||
| } from "./chunk-PE3GG3TN.js"; | ||
| // src/templates/layout/main.ts | ||
| var Layout = class extends BaseComponent { | ||
| cssFile = new URL("./layout/style.css", publicDirURL); | ||
| scriptFile = new URL("./layout/script.js", publicDirURL); | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML(props) { | ||
| return `<!DOCTYPE html> | ||
| <html lang="en"> | ||
| <head> | ||
| <meta charset="UTF-8" /> | ||
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | ||
| <title>${props.title}</title> | ||
| <!-- STYLES --> | ||
| <!-- GLOBAL SCRIPT --> | ||
| </head> | ||
| <body> | ||
| <div id="layout"> | ||
| ${await props.children()} | ||
| </div> | ||
| <!-- SCRIPTS --> | ||
| </body> | ||
| </html>`; | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI(props) { | ||
| return ` | ||
| ${await props.children()} | ||
| `; | ||
| } | ||
| }; | ||
| export { | ||
| Layout | ||
| }; |
| import { | ||
| colors, | ||
| htmlEscape | ||
| } from "./chunk-4L7RY2JA.js"; | ||
| import { | ||
| BaseComponent, | ||
| publicDirURL | ||
| } from "./chunk-PE3GG3TN.js"; | ||
| // src/templates/error_stack/main.ts | ||
| import { dump, themes } from "@poppinss/dumper/html"; | ||
| import { dump as dumpCli } from "@poppinss/dumper/console"; | ||
| var CHEVIRON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" width="24" height="24" stroke-width="2"> | ||
| <path d="M6 9l6 6l6 -6"></path> | ||
| </svg>`; | ||
| var EDITORS = { | ||
| textmate: "txmt://open?url=file://%f&line=%l", | ||
| macvim: "mvim://open?url=file://%f&line=%l", | ||
| emacs: "emacs://open?url=file://%f&line=%l", | ||
| sublime: "subl://open?url=file://%f&line=%l", | ||
| phpstorm: "phpstorm://open?file=%f&line=%l", | ||
| atom: "atom://core/open/file?filename=%f&line=%l", | ||
| vscode: "vscode://file/%f:%l" | ||
| }; | ||
| var ErrorStack = class extends BaseComponent { | ||
| cssFile = new URL("./error_stack/style.css", publicDirURL); | ||
| scriptFile = new URL("./error_stack/script.js", publicDirURL); | ||
| /** | ||
| * Returns the file's relative name from the CWD | ||
| */ | ||
| #getRelativeFileName(filePath) { | ||
| return filePath.replace(`${process.cwd()}/`, ""); | ||
| } | ||
| /** | ||
| * Returns the index of the frame that should be expanded by | ||
| * default | ||
| */ | ||
| #getFirstExpandedFrameIndex(frames) { | ||
| let expandAtIndex = frames.findIndex((frame) => frame.type === "app"); | ||
| if (expandAtIndex === -1) { | ||
| expandAtIndex = frames.findIndex((frame) => frame.type === "module"); | ||
| } | ||
| return expandAtIndex; | ||
| } | ||
| /** | ||
| * Returns the link to open the file within known code | ||
| * editors | ||
| */ | ||
| #getEditorLink(ide, frame) { | ||
| const editorURL = EDITORS[ide] || ide; | ||
| if (!editorURL || frame.type === "native") { | ||
| return { | ||
| text: this.#getRelativeFileName(frame.fileName) | ||
| }; | ||
| } | ||
| return { | ||
| href: editorURL.replace("%f", frame.fileName).replace("%l", String(frame.lineNumber)), | ||
| text: this.#getRelativeFileName(frame.fileName) | ||
| }; | ||
| } | ||
| /** | ||
| * Returns the HTML fragment for the frame location | ||
| */ | ||
| #renderFrameLocation(frame, ide) { | ||
| const { text, href } = this.#getEditorLink(ide, frame); | ||
| const fileName = `<a${href ? ` href="${href}"` : ""} class="stack-frame-filepath" title="${text}"> | ||
| ${htmlEscape(text)} | ||
| </a>`; | ||
| const functionName = frame.functionName ? `<span>in <code title="${frame.functionName}"> | ||
| ${htmlEscape(frame.functionName)} | ||
| </code></span>` : ""; | ||
| const loc = `<span>at line <code>${frame.lineNumber}:${frame.columnNumber}</code></span>`; | ||
| if (frame.type !== "native" && frame.source) { | ||
| return `<button class="stack-frame-location"> | ||
| ${fileName} ${functionName} ${loc} | ||
| </button>`; | ||
| } | ||
| return `<div class="stack-frame-location"> | ||
| ${fileName} ${functionName} ${loc} | ||
| </div>`; | ||
| } | ||
| /** | ||
| * Returns HTML fragment for the stack frame | ||
| */ | ||
| async #renderStackFrame(frame, index, expandAtIndex, props) { | ||
| const label = frame.type === "app" ? '<span class="frame-label">In App</span>' : ""; | ||
| const expandedClass = expandAtIndex === index ? " expanded" : ""; | ||
| const toggleButton = frame.type !== "native" && frame.source ? `<button class="stack-frame-toggle-indicator">${CHEVIRON}</button>` : ""; | ||
| return `<li class="stack-frame stack-frame-${frame.type}${expandedClass}"> | ||
| <div class="stack-frame-contents"> | ||
| ${this.#renderFrameLocation(frame, props.ide)} | ||
| <div class="stack-frame-extras"> | ||
| ${label} | ||
| ${toggleButton} | ||
| </div> | ||
| </div> | ||
| <div class="stack-frame-source"> | ||
| ${await props.sourceCodeRenderer(props.error, frame)} | ||
| </div> | ||
| </li>`; | ||
| } | ||
| /** | ||
| * Returns the ANSI output to print the stack frame on the | ||
| * terminal | ||
| */ | ||
| async #printStackFrame(frame, index, expandAtIndex, props) { | ||
| const fileName = this.#getRelativeFileName(frame.fileName); | ||
| const loc = `${fileName}:${frame.lineNumber}:${frame.columnNumber}`; | ||
| if (index === expandAtIndex) { | ||
| const functionName2 = frame.functionName ? `at ${frame.functionName} ` : ""; | ||
| const codeSnippet = await props.sourceCodeRenderer(props.error, frame); | ||
| return ` \u2043 ${functionName2}${colors.yellow(`(${loc})`)}${codeSnippet}`; | ||
| } | ||
| if (frame.type === "native") { | ||
| const functionName2 = frame.functionName ? `at ${colors.italic(frame.functionName)} ` : ""; | ||
| return colors.dim(` \u2043 ${functionName2}(${colors.italic(loc)})`); | ||
| } | ||
| const functionName = frame.functionName ? `at ${frame.functionName} ` : ""; | ||
| return ` \u2043 ${functionName}${colors.yellow(`(${loc})`)}`; | ||
| } | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML(props) { | ||
| const frames = await Promise.all( | ||
| props.error.frames.map((frame, index) => { | ||
| return this.#renderStackFrame( | ||
| frame, | ||
| index, | ||
| this.#getFirstExpandedFrameIndex(props.error.frames), | ||
| props | ||
| ); | ||
| }) | ||
| ); | ||
| return `<section> | ||
| <div class="card"> | ||
| <div class="card-heading"> | ||
| <div> | ||
| <h3 class="card-title"> | ||
| Stack Trace | ||
| </h3> | ||
| </div> | ||
| </div> | ||
| <div class="card-body"> | ||
| <div id="stack-frames-wrapper"> | ||
| <div id="stack-frames-header"> | ||
| <div id="all-frames-toggle-wrapper"> | ||
| <label id="all-frames-toggle"> | ||
| <input type="checkbox" /> | ||
| <span> View All Frames </span> | ||
| </label> | ||
| </div> | ||
| <div> | ||
| <div class="toggle-switch"> | ||
| <button id="formatted-frames-toggle" class="active"> Pretty </button> | ||
| <button id="raw-frames-toggle"> Raw </button> | ||
| </div> | ||
| </div> | ||
| </div> | ||
| <div id="stack-frames-body"> | ||
| <div id="stack-frames-formatted" class="visible"> | ||
| <ul id="stack-frames"> | ||
| ${frames.join("\n")} | ||
| </ul> | ||
| </div> | ||
| <div id="stack-frames-raw"> | ||
| ${dump(props.error.raw, { | ||
| styles: themes.cssVariables, | ||
| expand: true, | ||
| cspNonce: props.cspNonce, | ||
| inspectObjectPrototype: false, | ||
| inspectStaticMembers: false, | ||
| inspectArrayPrototype: false | ||
| })} | ||
| </div> | ||
| </div> | ||
| <div> | ||
| </div> | ||
| </div> | ||
| </section>`; | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI(props) { | ||
| const displayRaw = process.env.YOUCH_RAW; | ||
| if (displayRaw) { | ||
| const depth = Number.isNaN(Number(displayRaw)) ? 2 : Number(displayRaw); | ||
| return ` | ||
| ${colors.red("[RAW]")} | ||
| ${dumpCli(props.error.raw, { | ||
| depth, | ||
| inspectObjectPrototype: false, | ||
| inspectStaticMembers: false, | ||
| inspectArrayPrototype: false | ||
| })}`; | ||
| } | ||
| const frames = await Promise.all( | ||
| props.error.frames.map((frame, index) => { | ||
| return this.#printStackFrame( | ||
| frame, | ||
| index, | ||
| this.#getFirstExpandedFrameIndex(props.error.frames), | ||
| props | ||
| ); | ||
| }) | ||
| ); | ||
| if (frames.length) { | ||
| return ` | ||
| ${frames.join("\n")}`; | ||
| } | ||
| return ""; | ||
| } | ||
| }; | ||
| export { | ||
| ErrorStack | ||
| }; |
| import { | ||
| colors, | ||
| wordWrap | ||
| } from "./chunk-4L7RY2JA.js"; | ||
| import { | ||
| BaseComponent, | ||
| publicDirURL | ||
| } from "./chunk-PE3GG3TN.js"; | ||
| // src/templates/error_info/main.ts | ||
| var ERROR_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="24" height="24" fill="none"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 7v6m0 4.01.01-.011M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10Z"/></svg>`; | ||
| var HINT_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="24" height="24" fill="none"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="m21 2-1 1M3 2l1 1m17 13-1-1M3 16l1-1m5 3h6m-5 3h4M12 3C8 3 5.952 4.95 6 8c.023 1.487.5 2.5 1.5 3.5S9 13 9 15h6c0-2 .5-2.5 1.5-3.5h0c1-1 1.477-2.013 1.5-3.5.048-3.05-2-5-6-5Z"/></svg>`; | ||
| var COPY_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z" /><path d="M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1" /></svg>`; | ||
| function htmlAttributeEscape(value) { | ||
| return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">"); | ||
| } | ||
| var ErrorInfo = class extends BaseComponent { | ||
| cssFile = new URL("./error_info/style.css", publicDirURL); | ||
| scriptFile = new URL("./error_info/script.js", publicDirURL); | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML(props) { | ||
| return `<section> | ||
| <h4 id="error-name">${props.error.name}</h4> | ||
| <h1 id="error-title">${props.title}</h1> | ||
| </section> | ||
| <section> | ||
| <div class="card"> | ||
| <div class="card-body"> | ||
| <h2 id="error-message"> | ||
| <span>${ERROR_ICON_SVG}</span> | ||
| <span>${props.error.message}</span> | ||
| <button | ||
| id="copy-error-btn" | ||
| data-error-text="${htmlAttributeEscape(`${props.error.name}: ${props.error.message}`)}" | ||
| onclick="copyErrorMessage(this)" | ||
| title="Copy error message" | ||
| aria-label="Copy error message to clipboard" | ||
| > | ||
| ${COPY_ICON_SVG} | ||
| </button> | ||
| </h2> | ||
| ${props.error.hint ? `<div id="error-hint"> | ||
| <span>${HINT_ICON_SVG}</span> | ||
| <span>${props.error.hint}</span> | ||
| </div>` : ""} | ||
| </div> | ||
| </div> | ||
| </section>`; | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI(props) { | ||
| const errorMessage = colors.red( | ||
| `\u2139 ${wordWrap(`${props.error.name}: ${props.error.message}`, { | ||
| width: process.stdout.columns, | ||
| indent: " ", | ||
| newLine: "\n", | ||
| escape: (value) => value | ||
| })}` | ||
| ); | ||
| const hint = props.error.hint ? ` | ||
| ${colors.blue("\u25C9")} ${colors.dim().italic( | ||
| wordWrap(props.error.hint.replace(/(<([^>]+)>)/gi, ""), { | ||
| width: process.stdout.columns, | ||
| indent: " ", | ||
| newLine: "\n", | ||
| escape: (value) => value | ||
| }) | ||
| )}` : ""; | ||
| return `${errorMessage}${hint}`; | ||
| } | ||
| }; | ||
| export { | ||
| ErrorInfo | ||
| }; |
| import { | ||
| BaseComponent, | ||
| publicDirURL | ||
| } from "./chunk-PE3GG3TN.js"; | ||
| // src/templates/error_metadata/main.ts | ||
| import { dump, themes } from "@poppinss/dumper/html"; | ||
| var ErrorMetadata = class extends BaseComponent { | ||
| cssFile = new URL("./error_metadata/style.css", publicDirURL); | ||
| #primitives = ["string", "boolean", "number", "undefined"]; | ||
| /** | ||
| * Formats the error row value | ||
| */ | ||
| #formatRowValue(value, dumpValue, cspNonce) { | ||
| if (dumpValue === true) { | ||
| return dump(value, { styles: themes.cssVariables, cspNonce }); | ||
| } | ||
| if (this.#primitives.includes(typeof value) || value === null) { | ||
| return value; | ||
| } | ||
| return dump(value, { styles: themes.cssVariables, cspNonce }); | ||
| } | ||
| /** | ||
| * Returns HTML fragment with HTML table containing rows | ||
| * metadata section rows | ||
| */ | ||
| #renderRows(rows, cspNonce) { | ||
| return `<table class="card-table"> | ||
| <tbody> | ||
| ${rows.map((row) => { | ||
| return `<tr> | ||
| <td class="table-key">${row.key}</td> | ||
| <td class="table-value"> | ||
| ${this.#formatRowValue(row.value, row.dump, cspNonce)} | ||
| </td> | ||
| </tr>`; | ||
| }).join("\n")} | ||
| </tbody> | ||
| </table>`; | ||
| } | ||
| /** | ||
| * Renders each section with its rows inside a table | ||
| */ | ||
| #renderSection(section, rows, cspNonce) { | ||
| return `<div> | ||
| <h4 class="card-subtitle">${section}</h4> | ||
| ${Array.isArray(rows) ? this.#renderRows(rows, cspNonce) : `<span>${this.#formatRowValue(rows.value, rows.dump, cspNonce)}</span>`} | ||
| </div>`; | ||
| } | ||
| /** | ||
| * Renders each group as a card | ||
| */ | ||
| #renderGroup(group, sections, cspNonce) { | ||
| return `<section class="metadata-group"> | ||
| <div class="card"> | ||
| <div class="card-heading"> | ||
| <h3 class="card-title">${group}</h3> | ||
| </div> | ||
| <div class="card-body"> | ||
| ${Object.keys(sections).map((section) => this.#renderSection(section, sections[section], cspNonce)).join("\n")} | ||
| </div> | ||
| </div> | ||
| </section>`; | ||
| } | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML(props) { | ||
| const groups = props.metadata.toJSON(); | ||
| const groupsNames = Object.keys(groups); | ||
| if (!groupsNames.length) { | ||
| return ""; | ||
| } | ||
| return groupsNames.map((group) => this.#renderGroup(group, groups[group], props.cspNonce)).join("\n"); | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI() { | ||
| return ""; | ||
| } | ||
| }; | ||
| export { | ||
| ErrorMetadata | ||
| }; |
| // src/component.ts | ||
| import { readFile } from "fs/promises"; | ||
| var BaseComponent = class { | ||
| #cachedStyles; | ||
| #cachedScript; | ||
| /** | ||
| * A flag to know if we are in dev mode or not. In dev mode, | ||
| * the styles and scripts are refetched from the disk. | ||
| * Otherwise they are cached. | ||
| */ | ||
| #inDevMode; | ||
| /** | ||
| * Absolute path to the frontend JavaScript that should be | ||
| * injected within the HTML head. The JavaScript does not | ||
| * get transpiled, hence it should work cross browser by | ||
| * default. | ||
| */ | ||
| scriptFile; | ||
| /** | ||
| * Absolute path to the CSS file that should be injected | ||
| * within the HTML head. | ||
| */ | ||
| cssFile; | ||
| constructor(devMode) { | ||
| this.#inDevMode = devMode; | ||
| } | ||
| /** | ||
| * Returns the styles for the component. The null value | ||
| * is not returned if no styles are associated with | ||
| * the component | ||
| */ | ||
| async getStyles() { | ||
| if (!this.cssFile) { | ||
| return null; | ||
| } | ||
| if (this.#inDevMode) { | ||
| return await readFile(this.cssFile, "utf-8"); | ||
| } | ||
| this.#cachedStyles = this.#cachedStyles ?? await readFile(this.cssFile, "utf-8"); | ||
| return this.#cachedStyles; | ||
| } | ||
| /** | ||
| * Returns the frontend script for the component. The null | ||
| * value is not returned if no styles are associated | ||
| * with the component | ||
| */ | ||
| async getScript() { | ||
| if (!this.scriptFile) { | ||
| return null; | ||
| } | ||
| if (this.#inDevMode) { | ||
| return await readFile(this.scriptFile, "utf-8"); | ||
| } | ||
| this.#cachedScript = this.#cachedScript ?? await readFile(this.scriptFile, "utf-8"); | ||
| return this.#cachedScript; | ||
| } | ||
| }; | ||
| // src/public_dir.ts | ||
| var publicDirURL = new URL("./public/", import.meta.url); | ||
| export { | ||
| BaseComponent, | ||
| publicDirURL | ||
| }; |
| import { | ||
| colors | ||
| } from "./chunk-4L7RY2JA.js"; | ||
| import { | ||
| BaseComponent, | ||
| publicDirURL | ||
| } from "./chunk-PE3GG3TN.js"; | ||
| // src/templates/error_cause/main.ts | ||
| import { dump, themes } from "@poppinss/dumper/html"; | ||
| import { dump as dumpCli } from "@poppinss/dumper/console"; | ||
| var ErrorCause = class extends BaseComponent { | ||
| cssFile = new URL("./error_cause/style.css", publicDirURL); | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML(props) { | ||
| if (!props.error.cause) { | ||
| return ""; | ||
| } | ||
| return `<section> | ||
| <div class="card"> | ||
| <div class="card-heading"> | ||
| <div> | ||
| <h3 class="card-title"> | ||
| Error Cause | ||
| </h3> | ||
| </div> | ||
| </div> | ||
| <div class="card-body"> | ||
| <div id="error-cause"> | ||
| ${dump(props.error.cause, { | ||
| cspNonce: props.cspNonce, | ||
| styles: themes.cssVariables, | ||
| inspectObjectPrototype: false, | ||
| inspectStaticMembers: false, | ||
| inspectArrayPrototype: false | ||
| })} | ||
| </div> | ||
| </div> | ||
| </div> | ||
| </section>`; | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI(props) { | ||
| if (!props.error.cause) { | ||
| return ""; | ||
| } | ||
| let depth = process.env.YOUCH_CAUSE ? Number(process.env.YOUCH_CAUSE) : 2; | ||
| if (Number.isNaN(depth)) { | ||
| depth = 2; | ||
| } | ||
| return ` | ||
| ${colors.red("[CAUSE]")} | ||
| ${dumpCli(props.error.cause, { | ||
| depth, | ||
| inspectObjectPrototype: false, | ||
| inspectStaticMembers: false, | ||
| inspectArrayPrototype: false | ||
| })}`; | ||
| } | ||
| }; | ||
| export { | ||
| ErrorCause | ||
| }; |
| .metadata-group .card-subtitle + span { | ||
| word-break: break-word; | ||
| } |
| export declare const ISR_URL_PARAM = "__isr_route"; | ||
| export declare function isrRouteRewrite(reqUrl: string, xNowRouteMatches: string | null): [pathname: string, search: string] | undefined; |
| export const ISR_URL_PARAM = "__isr_route"; | ||
| export function isrRouteRewrite(reqUrl, xNowRouteMatches) { | ||
| if (xNowRouteMatches) { | ||
| const isrURL = new URLSearchParams(xNowRouteMatches).get(ISR_URL_PARAM); | ||
| if (isrURL) { | ||
| return [decodeURIComponent(isrURL), ""]; | ||
| } | ||
| } else { | ||
| const queryIndex = reqUrl.indexOf("?"); | ||
| if (queryIndex !== -1) { | ||
| const params = new URLSearchParams(reqUrl.slice(queryIndex + 1)); | ||
| const isrURL = params.get(ISR_URL_PARAM); | ||
| if (isrURL) { | ||
| params.delete(ISR_URL_PARAM); | ||
| return [decodeURIComponent(isrURL), params.toString()]; | ||
| } | ||
| } | ||
| } | ||
| } |
| import { parentPort, threadId, workerData } from "node:worker_threads"; | ||
| import { Agent } from "undici"; | ||
| import { ModuleRunner, ESModulesEvaluator } from "vite/module-runner"; | ||
| import { getSocketAddress, isSocketSupported } from "get-port-please"; | ||
| // ----- Environment runners ----- | ||
| const envs = (globalThis.__nitro_vite_envs__ ??= { | ||
| nitro: undefined, | ||
| ssr: undefined, | ||
| }); | ||
| class EnvRunner { | ||
| constructor({ name, entry }) { | ||
| this.name = name; | ||
| this.entryPath = entry; | ||
| this.entry = undefined; | ||
| this.entryError = undefined; | ||
| // Create Vite Module Runner | ||
| // https://vite.dev/guide/api-environment-runtimes.html#modulerunner | ||
| this.runnerHooks = {}; | ||
| this.runner = new ModuleRunner( | ||
| { | ||
| transport: { | ||
| connect({ onMessage, onDisconnection }) { | ||
| parentPort.on("message", (payload) => { | ||
| if (payload?.type === "custom" && payload.viteEnv === name) { | ||
| onMessage(payload); | ||
| } | ||
| }); | ||
| parentPort.on("close", onDisconnection); | ||
| }, | ||
| send(payload) { | ||
| parentPort.postMessage({ ...payload, viteEnv: name }); | ||
| }, | ||
| }, | ||
| }, | ||
| new ESModulesEvaluator(), | ||
| process.env.NITRO_DEBUG ? console.debug : undefined | ||
| ); | ||
| this.reload(); | ||
| } | ||
| async reload() { | ||
| try { | ||
| this.entry = await this.runner.import(this.entryPath); | ||
| this.entryError = undefined; | ||
| } catch (error) { | ||
| console.error(error); | ||
| this.entryError = error; | ||
| } | ||
| } | ||
| async fetch(req, init) { | ||
| if (this.entryError) { | ||
| return renderError(req, this.entryError); | ||
| } | ||
| for (let i = 0; i < 5 && !(this.entry || this.entryError); i++) { | ||
| await new Promise((r) => setTimeout(r, 100 * Math.pow(2, i))); | ||
| } | ||
| if (this.entryError) { | ||
| return renderError(req, this.entryError); | ||
| } | ||
| if (!this.entry) { | ||
| throw httpError(503, `Vite environment "${this.name}" is unavailable`); | ||
| } | ||
| try { | ||
| const entryFetch = this.entry.fetch || this.entry.default?.fetch; | ||
| if (!entryFetch) { | ||
| throw httpError( | ||
| 500, | ||
| `No fetch handler exported from ${this.entryPath}` | ||
| ); | ||
| } | ||
| return await entryFetch(req, init); | ||
| } catch (error) { | ||
| return renderError(req, error); | ||
| } | ||
| } | ||
| } | ||
| // ----- RPC listeners ----- | ||
| const viteHostRequests = new Map(); | ||
| async function requestToViteHost( | ||
| name, | ||
| data, | ||
| id = Math.random().toString(16).slice(2), | ||
| timeout = 3000 | ||
| ) { | ||
| setTimeout(() => { | ||
| if (viteHostRequests.has(id)) { | ||
| viteHostRequests.delete(id); | ||
| reject(new Error(`Request to vite host timed out (${name}:${id})`)); | ||
| } | ||
| }, timeout); | ||
| let resolve, reject; | ||
| const promise = new Promise((_resolve, _reject) => { | ||
| resolve = (value) => { | ||
| viteHostRequests.delete(id); | ||
| return _resolve(value); | ||
| }; | ||
| reject = (err) => { | ||
| viteHostRequests.delete(id); | ||
| return _reject(err); | ||
| }; | ||
| }); | ||
| viteHostRequests.set(id, { resolve, reject }); | ||
| parentPort.postMessage({ | ||
| type: "custom", | ||
| event: "nitro:vite-invoke", | ||
| data: { name, id, data }, | ||
| }); | ||
| return promise; | ||
| } | ||
| parentPort.on("message", (payload) => { | ||
| if (payload?.type !== "custom") { | ||
| return; | ||
| } | ||
| switch (payload.event) { | ||
| case "nitro:vite-server-addr": { | ||
| viteServerAddr = payload.data; | ||
| break; | ||
| } | ||
| case "nitro:vite-env": { | ||
| const { name, entry } = payload.data; | ||
| if (envs[name]) { | ||
| console.error(`Vite environment "${name}" already registered!`); | ||
| } else { | ||
| envs[name] = new EnvRunner({ name, entry }); | ||
| } | ||
| break; | ||
| } | ||
| case "nitro:vite-invoke-response": { | ||
| const { id, data: response } = payload.data; | ||
| const req = viteHostRequests.get(id); | ||
| if (req) { | ||
| if (response.error) { | ||
| req.reject(response.error); | ||
| } else { | ||
| req.resolve(response.data); | ||
| } | ||
| } | ||
| break; | ||
| } | ||
| } | ||
| }); | ||
| // Trap unhandled errors to avoid worker crash | ||
| process.on("unhandledRejection", (error) => console.error(error)); | ||
| process.on("uncaughtException", (error) => console.error(error)); | ||
| // ----- RSC Support ----- | ||
| // define __VITE_ENVIRONMENT_RUNNER_IMPORT__ for RSC support | ||
| // https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-rsc/README.md#__vite_environment_runner_import__ | ||
| globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__ = async function ( | ||
| environmentName, | ||
| id | ||
| ) { | ||
| const env = envs[environmentName]; | ||
| if (!env) { | ||
| throw new Error(`Vite environment "${environmentName}" is not registered`); | ||
| } | ||
| return env.runner.import(id); | ||
| }; | ||
| // ----- Server ----- | ||
| async function reload() { | ||
| try { | ||
| await Promise.all(Object.values(envs).map((env) => env?.reload())); | ||
| } catch (error) { | ||
| console.error(error); | ||
| } | ||
| } | ||
| // eslint-disable-next-line unicorn/prefer-top-level-await | ||
| reload(); | ||
| if (workerData.server) { | ||
| const { createServer } = await import("node:http"); | ||
| const { toNodeHandler } = await import("srvx/node"); | ||
| const server = createServer( | ||
| toNodeHandler(async (req, init) => { | ||
| const viteEnv = | ||
| init?.viteEnv || req?.headers.get("x-vite-env") || "nitro"; // TODO | ||
| const env = envs[viteEnv]; | ||
| if (!env) { | ||
| return renderError( | ||
| req, | ||
| httpError(500, `Unknown vite environment "${viteEnv}"`) | ||
| ); | ||
| } | ||
| return env.fetch(req, init); | ||
| }) | ||
| ); | ||
| server.on("upgrade", (req, socket, head) => { | ||
| const handleUpgrade = envs["nitro"]?.entry?.handleUpgrade; | ||
| handleUpgrade?.(req, socket, head); | ||
| }); | ||
| parentPort.on("message", async (message) => { | ||
| if (message?.type === "full-reload") { | ||
| await reload(); | ||
| } else if (message?.event === "shutdown") { | ||
| server.close(() => { | ||
| parentPort.postMessage({ event: "exit" }); | ||
| }); | ||
| } | ||
| }); | ||
| await listen(server); | ||
| const address = server.address(); | ||
| parentPort?.postMessage({ | ||
| event: "listen", | ||
| address: | ||
| typeof address === "string" | ||
| ? { socketPath: address } | ||
| : { host: "localhost", port: address?.port }, | ||
| }); | ||
| } | ||
| // ----- HTML Transform ----- | ||
| globalThis.__transform_html__ = async function (html) { | ||
| html = await requestToViteHost("transformHTML", html).catch((error) => { | ||
| console.warn("Failed to transform HTML via Vite:", error); | ||
| return html; | ||
| }); | ||
| return html; | ||
| }; | ||
| // ----- Error handling ----- | ||
| function httpError(status, message) { | ||
| const error = new Error(message || `HTTP Error ${status}`); | ||
| error.status = status; | ||
| error.name = "NitroViteError"; | ||
| return error; | ||
| } | ||
| async function renderError(req, error) { | ||
| if (req.headers.get("accept")?.includes("application/json")) { | ||
| return new Response( | ||
| JSON.stringify( | ||
| { | ||
| status: error.status || 500, | ||
| name: error.name || "Error", | ||
| message: error.message, | ||
| stack: (error.stack || "") | ||
| .split("\n") | ||
| .splice(1) | ||
| .map((l) => l.trim()), | ||
| }, | ||
| null, | ||
| 2 | ||
| ), | ||
| { | ||
| status: error.status || 500, | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| "Cache-Control": "no-store, max-age=0, must-revalidate", | ||
| Pragma: "no-cache", | ||
| Expires: "0", | ||
| }, | ||
| } | ||
| ); | ||
| } | ||
| const { Youch } = await import("youch"); | ||
| const youch = new Youch(); | ||
| return new Response(await youch.toHTML(error), { | ||
| status: error.status || 500, | ||
| headers: { | ||
| "Content-Type": "text/html", | ||
| "Cache-Control": "no-store, max-age=0, must-revalidate", | ||
| Pragma: "no-cache", | ||
| Expires: "0", | ||
| }, | ||
| }); | ||
| } | ||
| // ----- Internal Utils ----- | ||
| async function listen(server) { | ||
| const listenAddr = (await isSocketSupported()) | ||
| ? getSocketAddress({ | ||
| name: `nitro-vite-${threadId}`, | ||
| pid: true, | ||
| random: true, | ||
| }) | ||
| : { port: 0, host: "localhost" }; | ||
| return new Promise((resolve, reject) => { | ||
| try { | ||
| server.listen(listenAddr, () => resolve()); | ||
| } catch (error) { | ||
| reject(error); | ||
| } | ||
| }); | ||
| } | ||
| function fetchAddress(addr, input, inputInit) { | ||
| let url; | ||
| let init; | ||
| if (input instanceof Request) { | ||
| url = new URL(input.url); | ||
| init = { | ||
| method: input.method, | ||
| headers: input.headers, | ||
| body: input.body, | ||
| ...inputInit, | ||
| }; | ||
| } else { | ||
| url = new URL(input); | ||
| init = inputInit; | ||
| } | ||
| init = { | ||
| duplex: "half", | ||
| redirect: "manual", | ||
| ...init, | ||
| }; | ||
| if (addr.socketPath) { | ||
| url.protocol = "http:"; | ||
| return fetch(url, { | ||
| ...init, | ||
| ...fetchSocketOptions(addr.socketPath), | ||
| }); | ||
| } | ||
| const origin = `http://${addr.host}${addr.port ? `:${addr.port}` : ""}`; | ||
| const outURL = new URL(url.pathname + url.search, origin); | ||
| return fetch(outURL, init); | ||
| } | ||
| function fetchSocketOptions(socketPath) { | ||
| if ("Bun" in globalThis) { | ||
| // https://bun.sh/guides/http/fetch-unix | ||
| return { unix: socketPath }; | ||
| } | ||
| if ("Deno" in globalThis) { | ||
| // https://github.com/denoland/deno/pull/29154 | ||
| return { | ||
| client: Deno.createHttpClient({ | ||
| // @ts-expect-error Missing types? | ||
| transport: "unix", | ||
| path: socketPath, | ||
| }), | ||
| }; | ||
| } | ||
| // https://github.com/nodejs/undici/issues/2970 | ||
| return { | ||
| dispatcher: new Agent({ connect: { socketPath } }), | ||
| }; | ||
| } |
| export {}; |
| import consola from "consola"; | ||
| import { isTest } from "std-env"; | ||
| if (!isTest) { | ||
| consola.warn("Nitro runtime imports detected without a builder or Nitro plugin. A stub implementation will be used."); | ||
| } |
| import "./_runtime_warn.mjs"; | ||
| import type { Connector } from "db0"; | ||
| export declare const connectionConfigs: { | ||
| [name: string]: { | ||
| connector: (options: any) => Connector; | ||
| options: any; | ||
| }; | ||
| }; |
| import "./_runtime_warn.mjs"; | ||
| export const connectionConfigs = {}; |
| import "./_runtime_warn.mjs"; | ||
| import type { NitroErrorHandler } from "nitro/types"; | ||
| type EParams = Parameters<NitroErrorHandler>; | ||
| type EReturn = ReturnType<NitroErrorHandler>; | ||
| declare const errorHandler: (error: EParams[0], event: EParams[1]) => EReturn; | ||
| export default errorHandler; |
| import "./_runtime_warn.mjs"; | ||
| import { toResponse } from "h3"; | ||
| const errorHandler = (error, event) => { | ||
| if (error.status !== 404) { | ||
| console.error(error); | ||
| } | ||
| return toResponse(error, event); | ||
| }; | ||
| export default errorHandler; |
| import "./_runtime_warn.mjs"; | ||
| export declare const hasRoutes: boolean; | ||
| export declare const hasRouteRules: boolean; | ||
| export declare const hasGlobalMiddleware: boolean; | ||
| export declare const hasRoutedMiddleware: boolean; | ||
| export declare const hasPlugins: boolean; | ||
| export declare const hasHooks: boolean; |
| import "./_runtime_warn.mjs"; | ||
| export const hasRoutes = true; | ||
| export const hasRouteRules = true; | ||
| export const hasGlobalMiddleware = true; | ||
| export const hasRoutedMiddleware = true; | ||
| export const hasPlugins = true; | ||
| export const hasHooks = true; |
| import "./_runtime_warn.mjs"; | ||
| import type { NitroAppPlugin } from "nitro/types"; | ||
| export declare const plugins: NitroAppPlugin[]; |
| import "./_runtime_warn.mjs"; | ||
| export const plugins = []; |
| import "./_runtime_warn.mjs"; | ||
| declare const _default: {}; | ||
| export default _default; |
| import "./_runtime_warn.mjs"; | ||
| export default {}; |
| import "./_runtime_warn.mjs"; | ||
| import type { PublicAsset } from "nitro/types"; | ||
| export declare const publicAssetBases: string[]; | ||
| export declare const isPublicAssetURL: (id: string) => boolean; | ||
| export declare const getPublicAssetMeta: (id: string) => { | ||
| maxAge?: number; | ||
| } | null; | ||
| export declare const readAsset: (id: string) => Promise<Buffer>; | ||
| export declare const getAsset: (id: string) => PublicAsset | null; |
| import "./_runtime_warn.mjs"; | ||
| export const publicAssetBases = []; | ||
| export const isPublicAssetURL = () => false; | ||
| export const getPublicAssetMeta = () => null; | ||
| export const readAsset = async () => { | ||
| throw new Error("Asset not found"); | ||
| }; | ||
| export const getAsset = () => null; |
| import "./_runtime_warn.mjs"; | ||
| export declare function rendererTemplate(_req: Request): string | Promise<string>; | ||
| export declare const rendererTemplateFile: string | undefined; | ||
| export declare const isStaticTemplate: boolean | undefined; |
| import "./_runtime_warn.mjs"; | ||
| export function rendererTemplate(_req) { | ||
| return `<!-- Renderer template not available -->`; | ||
| } | ||
| // dev only | ||
| export const rendererTemplateFile = undefined; | ||
| export const isStaticTemplate = undefined; |
| import "./_runtime_warn.mjs"; | ||
| import type { NitroRouteMeta } from "nitro/types"; | ||
| export declare const handlersMeta: { | ||
| route?: string; | ||
| method?: string; | ||
| meta?: NitroRouteMeta; | ||
| }[]; |
| import "./_runtime_warn.mjs"; | ||
| export const handlersMeta = []; |
| import "./_runtime_warn.mjs"; | ||
| import type { Middleware, H3Route } from "h3"; | ||
| import type { MatchedRoute } from "rou3"; | ||
| import type { MatchedRouteRule } from "nitro/types"; | ||
| export declare function findRoute(_method: string, _path: string): MatchedRoute<H3Route> | undefined; | ||
| export declare function findRouteRules(_method: string, _path: string): MatchedRoute<MatchedRouteRule[]>[]; | ||
| export declare const globalMiddleware: Middleware[]; | ||
| export declare function findRoutedMiddleware(_method: string, _path: string): MatchedRoute<Middleware>[]; |
| import "./_runtime_warn.mjs"; | ||
| export function findRoute(_method, _path) { | ||
| return undefined; | ||
| } | ||
| export function findRouteRules(_method, _path) { | ||
| return []; | ||
| } | ||
| export const globalMiddleware = []; | ||
| export function findRoutedMiddleware(_method, _path) { | ||
| return []; | ||
| } |
| import "./_runtime_warn.mjs"; | ||
| import type { NitroRuntimeConfig } from "nitro/types"; | ||
| export declare const runtimeConfig: NitroRuntimeConfig; |
| import "./_runtime_warn.mjs"; | ||
| export const runtimeConfig = { | ||
| app: {}, | ||
| nitro: {} | ||
| }; |
| import "./_runtime_warn.mjs"; | ||
| import type { AssetMeta } from "nitro/types"; | ||
| export declare const assets: unknown; | ||
| export declare function readAsset<T = any>(_id: string): Promise<T>; | ||
| export declare function statAsset(_id: string): Promise<AssetMeta>; | ||
| export declare function getKeys(): Promise<string[]>; |
| import "./_runtime_warn.mjs"; | ||
| import { createStorage } from "unstorage"; | ||
| export const assets = createStorage(); | ||
| export function readAsset(_id) { | ||
| return Promise.resolve({}); | ||
| } | ||
| export function statAsset(_id) { | ||
| return Promise.resolve({}); | ||
| } | ||
| export function getKeys() { | ||
| return Promise.resolve([]); | ||
| } |
| import "./_runtime_warn.mjs"; | ||
| import { type Storage } from "unstorage"; | ||
| export declare function initStorage(): Storage; |
| import "./_runtime_warn.mjs"; | ||
| import { createStorage } from "unstorage"; | ||
| export function initStorage() { | ||
| return createStorage(); | ||
| } |
| import "./_runtime_warn.mjs"; | ||
| import type { Task, TaskMeta } from "nitro/types"; | ||
| export declare const tasks: Record<string, { | ||
| resolve?: () => Promise<Task>; | ||
| meta: TaskMeta; | ||
| }>; | ||
| export declare const scheduledTasks: false | { | ||
| cron: string; | ||
| tasks: string[]; | ||
| }[]; |
| import "./_runtime_warn.mjs"; | ||
| export const tasks = {}; | ||
| export const scheduledTasks = []; |
| type FetchableEnv = { | ||
| fetch: (request: Request) => Response | Promise<Response>; | ||
| }; | ||
| declare global { | ||
| var __nitro_vite_envs__: Record<string, FetchableEnv>; | ||
| } | ||
| export declare function fetchViteEnv(viteEnvName: string, input: RequestInfo | URL, init?: RequestInit); | ||
| export {}; |
| import { HTTPError, toRequest } from "h3"; | ||
| export function fetchViteEnv(viteEnvName, input, init) { | ||
| const envs = globalThis.__nitro_vite_envs__ || {}; | ||
| const viteEnv = envs[viteEnvName]; | ||
| if (!viteEnv) { | ||
| throw HTTPError.status(404); | ||
| } | ||
| return Promise.resolve(viteEnv.fetch(toRequest(input, init))); | ||
| } |
| export * from "h3"; |
| export * from "h3"; |
| // Based on https://github.com/hi-ogawa/vite-plugin-fullstack/blob/main/types/query.d.ts | ||
| type ImportAssetsResult = ImportAssetsResultRaw & { | ||
| merge(...args: ImportAssetsResultRaw[]): ImportAssetsResult; | ||
| }; | ||
| type ImportAssetsResultRaw = { | ||
| entry?: string; | ||
| js: { href: string }[]; | ||
| css: { href: string; "data-vite-dev-id"?: string }[]; | ||
| }; | ||
| declare module "*?assets" { | ||
| const assets: ImportAssetsResult; | ||
| export default assets; | ||
| } | ||
| declare module "*?assets=client" { | ||
| const assets: ImportAssetsResult; | ||
| export default assets; | ||
| } | ||
| declare module "*?assets=ssr" { | ||
| const assets: ImportAssetsResult; | ||
| export default assets; | ||
| } |
| // eslint-disable-next-line unicorn/require-module-specifiers | ||
| export {}; |
+29
-63
@@ -1,52 +0,18 @@ | ||
| import { O as relative, T as normalize, n as debounce, w as join } from "../_libs/c12.mjs"; | ||
| import "../_libs/gen-mapping.mjs"; | ||
| import "../_libs/magic-string.mjs"; | ||
| import "../_libs/acorn.mjs"; | ||
| import "../_libs/confbox.mjs"; | ||
| import { f as sanitizeFilePath } from "../_libs/local-pkg.mjs"; | ||
| import "../_libs/js-tokens.mjs"; | ||
| import "../_libs/strip-literal.mjs"; | ||
| import "../_libs/unimport.mjs"; | ||
| import "../_libs/picomatch.mjs"; | ||
| import "../_libs/fdir.mjs"; | ||
| import "../_libs/tinyglobby.mjs"; | ||
| import "../_common.mjs"; | ||
| import { _ as writeTypes, at as join, d as libChunkName, f as baseBuildConfig, h as writeBuildInfo, l as NODE_MODULES_RE, n as baseBuildPlugins, st as relative, u as getChunkName } from "./common.mjs"; | ||
| import { i as debounce } from "../_libs/rc9+c12+dotenv.mjs"; | ||
| import { t as formatCompatibilityDate } from "../_libs/compatx.mjs"; | ||
| import "../_libs/std-env.mjs"; | ||
| import "../_libs/dot-prop.mjs"; | ||
| import "../_chunks/C7CbzoI1.mjs"; | ||
| import { i as scanHandlers, n as writeTypes } from "../_chunks/ANM1K1bE.mjs"; | ||
| import "../_libs/mime.mjs"; | ||
| import "../_libs/pathe.mjs"; | ||
| import "../_libs/untyped.mjs"; | ||
| import "../_libs/knitwork.mjs"; | ||
| import { n as writeBuildInfo } from "./common.mjs"; | ||
| import { i as watch$1 } from "../_libs/chokidar.mjs"; | ||
| import "../_libs/estree-walker.mjs"; | ||
| import "../_libs/plugin-commonjs.mjs"; | ||
| import { n as baseBuildConfig, t as baseBuildPlugins } from "./common2.mjs"; | ||
| import "../_libs/remapping.mjs"; | ||
| import "../_libs/unwasm.mjs"; | ||
| import "../_libs/plugin-replace.mjs"; | ||
| import "../_libs/etag.mjs"; | ||
| import "../_libs/duplexer.mjs"; | ||
| import "../_libs/gzip-size.mjs"; | ||
| import "../_libs/pretty-bytes.mjs"; | ||
| import { t as generateFSTree } from "../_chunks/BX9-zVkM.mjs"; | ||
| import { n as scanHandlers } from "../_chunks/nitro2.mjs"; | ||
| import { n as watch$1 } from "../_libs/readdirp+chokidar.mjs"; | ||
| import { t as generateFSTree } from "../_chunks/utils.mjs"; | ||
| import { builtinModules } from "node:module"; | ||
| import { watch } from "node:fs"; | ||
| import { defu } from "defu"; | ||
| import { runtimeDir } from "nitro/meta"; | ||
| //#region src/build/rolldown/config.ts | ||
| const getRolldownConfig = (nitro) => { | ||
| const getRolldownConfig = async (nitro) => { | ||
| const base = baseBuildConfig(nitro); | ||
| const chunkNamePrefixes = [ | ||
| [runtimeDir, "nitro"], | ||
| [base.presetsDir, "nitro"], | ||
| ["\0raw:", "raw"], | ||
| ["\0nitro-wasm:", "wasm"], | ||
| ["\0", "virtual"] | ||
| ]; | ||
| const tsc = nitro.options.typescript.tsConfig?.compilerOptions; | ||
| let config = { | ||
| platform: nitro.options.node ? "node" : "neutral", | ||
| cwd: nitro.options.rootDir, | ||
@@ -59,7 +25,6 @@ input: nitro.options.entry, | ||
| ], | ||
| plugins: [...baseBuildPlugins(nitro, base)], | ||
| plugins: [...await baseBuildPlugins(nitro, base)], | ||
| resolve: { | ||
| alias: base.aliases, | ||
| extensions: base.extensions, | ||
| mainFields: ["main"], | ||
| conditionNames: nitro.options.exportConditions | ||
@@ -78,3 +43,6 @@ }, | ||
| onwarn(warning, warn) { | ||
| if (!["CIRCULAR_DEPENDENCY", "EVAL"].includes(warning.code || "") && !warning.message.includes("Unsupported source map comment")) warn(warning); | ||
| if (!base.ignoreWarningCodes.has(warning.code || "")) { | ||
| console.log(warning.code); | ||
| warn(warning); | ||
| } | ||
| }, | ||
@@ -84,20 +52,14 @@ treeshake: { moduleSideEffects(id) { | ||
| } }, | ||
| optimization: { inlineConst: true }, | ||
| output: { | ||
| format: "esm", | ||
| entryFileNames: "index.mjs", | ||
| chunkFileNames: (chunk) => getChunkName(chunk, nitro), | ||
| codeSplitting: { groups: [{ | ||
| test: NODE_MODULES_RE, | ||
| name: (id) => libChunkName(id) | ||
| }] }, | ||
| dir: nitro.options.output.serverDir, | ||
| entryFileNames: "index.mjs", | ||
| minify: nitro.options.minify, | ||
| chunkFileNames(chunk) { | ||
| const id = normalize(chunk.moduleIds.at(-1) || ""); | ||
| for (const [dir, name] of chunkNamePrefixes) if (id.startsWith(dir)) return `chunks/${name}/[name].mjs`; | ||
| const routeHandler = nitro.options.handlers.find((h) => id.startsWith(h.handler)) || nitro.scannedHandlers.find((h) => id.startsWith(h.handler)); | ||
| if (routeHandler?.route) return `chunks/routes${routeHandler.route.replace(/:([^/]+)/g, "_$1").replace(/\/[^/]+$/g, "").replace(/[^a-zA-Z0-9/_-]/g, "_") || "/"}/[name].mjs`; | ||
| if (Object.entries(nitro.options.tasks).find(([_, task]) => task.handler === id)) return `chunks/tasks/[name].mjs`; | ||
| return `chunks/_/[name].mjs`; | ||
| }, | ||
| inlineDynamicImports: nitro.options.inlineDynamicImports, | ||
| format: "esm", | ||
| exports: "auto", | ||
| intro: "", | ||
| outro: "", | ||
| sanitizeFileName: sanitizeFilePath, | ||
| minify: nitro.options.minify ? true : "dce-only", | ||
| sourcemap: nitro.options.sourcemap, | ||
@@ -109,3 +71,5 @@ sourcemapIgnoreList(relativePath) { | ||
| }; | ||
| config = defu(nitro.options.rollupConfig, config); | ||
| config = defu(nitro.options.rolldownConfig, nitro.options.rollupConfig, config); | ||
| const outputConfig = config.output; | ||
| if (outputConfig.inlineDynamicImports || outputConfig.format === "iife") delete outputConfig.codeSplitting; | ||
| return config; | ||
@@ -168,3 +132,5 @@ }; | ||
| break; | ||
| case "ERROR": nitro$1.hooks.callHook("dev:error", event.error); | ||
| case "ERROR": | ||
| nitro$1.logger.error(event.error); | ||
| nitro$1.hooks.callHook("dev:error", event.error); | ||
| } | ||
@@ -205,3 +171,3 @@ }); | ||
| await nitro.hooks.callHook("build:before", nitro); | ||
| const config = getRolldownConfig(nitro); | ||
| const config = await getRolldownConfig(nitro); | ||
| await nitro.hooks.callHook("rollup:before", nitro, config); | ||
@@ -208,0 +174,0 @@ return nitro.options.dev ? watchDev(nitro, config) : buildProduction(nitro, config); |
+22
-110
@@ -1,89 +0,19 @@ | ||
| import { C as isAbsolute, O as relative, T as normalize, n as debounce, w as join } from "../_libs/c12.mjs"; | ||
| import "../_libs/gen-mapping.mjs"; | ||
| import "../_libs/magic-string.mjs"; | ||
| import "../_libs/acorn.mjs"; | ||
| import "../_libs/confbox.mjs"; | ||
| import { f as sanitizeFilePath } from "../_libs/local-pkg.mjs"; | ||
| import "../_libs/js-tokens.mjs"; | ||
| import "../_libs/strip-literal.mjs"; | ||
| import "../_libs/unimport.mjs"; | ||
| import "../_libs/picomatch.mjs"; | ||
| import "../_libs/fdir.mjs"; | ||
| import "../_libs/tinyglobby.mjs"; | ||
| import "../_common.mjs"; | ||
| import { _ as writeTypes, at as join, d as libChunkName, f as baseBuildConfig, h as writeBuildInfo, it as isAbsolute, l as NODE_MODULES_RE, n as baseBuildPlugins, st as relative, t as oxc, u as getChunkName } from "./common.mjs"; | ||
| import { i as debounce } from "../_libs/rc9+c12+dotenv.mjs"; | ||
| import { t as formatCompatibilityDate } from "../_libs/compatx.mjs"; | ||
| import "../_libs/std-env.mjs"; | ||
| import "../_libs/dot-prop.mjs"; | ||
| import "../_chunks/C7CbzoI1.mjs"; | ||
| import { i as scanHandlers, n as writeTypes } from "../_chunks/ANM1K1bE.mjs"; | ||
| import "../_libs/mime.mjs"; | ||
| import "../_libs/pathe.mjs"; | ||
| import "../_libs/untyped.mjs"; | ||
| import "../_libs/knitwork.mjs"; | ||
| import { n as writeBuildInfo } from "./common.mjs"; | ||
| import { i as watch$1 } from "../_libs/chokidar.mjs"; | ||
| import { n as scanHandlers } from "../_chunks/nitro2.mjs"; | ||
| import { n as watch$1 } from "../_libs/readdirp+chokidar.mjs"; | ||
| import { t as alias } from "../_libs/plugin-alias.mjs"; | ||
| import "../_libs/estree-walker.mjs"; | ||
| import { t as commonjs } from "../_libs/plugin-commonjs.mjs"; | ||
| import { t as inject } from "../_libs/plugin-inject.mjs"; | ||
| import { n as baseBuildConfig, t as baseBuildPlugins } from "./common2.mjs"; | ||
| import "../_libs/remapping.mjs"; | ||
| import "../_libs/unwasm.mjs"; | ||
| import "../_libs/plugin-replace.mjs"; | ||
| import "../_libs/etag.mjs"; | ||
| import "../_libs/duplexer.mjs"; | ||
| import "../_libs/gzip-size.mjs"; | ||
| import "../_libs/pretty-bytes.mjs"; | ||
| import { t as generateFSTree } from "../_chunks/BX9-zVkM.mjs"; | ||
| import "../_libs/commondir.mjs"; | ||
| import "../_libs/is-reference.mjs"; | ||
| import { n as inject } from "../_libs/plugin-inject.mjs"; | ||
| import { t as generateFSTree } from "../_chunks/utils.mjs"; | ||
| import { t as commonjs } from "../_libs/commondir+is-reference.mjs"; | ||
| import { t as json } from "../_libs/plugin-json.mjs"; | ||
| import "../_libs/deepmerge.mjs"; | ||
| import "../_libs/is-module.mjs"; | ||
| import { t as nodeResolve } from "../_libs/plugin-node-resolve.mjs"; | ||
| import "../_libs/path-parse.mjs"; | ||
| import "../_libs/function-bind.mjs"; | ||
| import "../_libs/hasown.mjs"; | ||
| import "../_libs/is-core-module.mjs"; | ||
| import { t as nodeResolve } from "../_libs/hasown+resolve+deepmerge.mjs"; | ||
| import { watch } from "node:fs"; | ||
| import { defu } from "defu"; | ||
| import { runtimeDir } from "nitro/meta"; | ||
| import { transform } from "oxc-transform"; | ||
| import { minify } from "oxc-minify"; | ||
| //#region src/build/plugins/oxc.ts | ||
| function oxc(options) { | ||
| const filter = (id) => !/node_modules/.test(id) && /\.[mj]?[jt]sx?$/.test(id); | ||
| return { | ||
| name: "nitro:oxc", | ||
| async transform(code, id) { | ||
| if (!filter(id)) return null; | ||
| return transform(id, code, { | ||
| sourcemap: options.sourcemap, | ||
| ...options.transform | ||
| }); | ||
| }, | ||
| async renderChunk(code, chunk) { | ||
| if (options.minify) return minify(chunk.fileName, code, { | ||
| sourcemap: options.sourcemap, | ||
| ...typeof options.minify === "object" ? options.minify : {} | ||
| }); | ||
| return null; | ||
| } | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/build/rollup/config.ts | ||
| const getRollupConfig = (nitro) => { | ||
| const getRollupConfig = async (nitro) => { | ||
| const base = baseBuildConfig(nitro); | ||
| const chunkNamePrefixes = [ | ||
| [runtimeDir, "nitro"], | ||
| [base.presetsDir, "nitro"], | ||
| ["\0raw:", "raw"], | ||
| ["\0nitro-wasm:", "wasm"], | ||
| ["\0", "virtual"] | ||
| ]; | ||
| function getChunkGroup(id) { | ||
| if (id.startsWith(runtimeDir) || id.startsWith(base.presetsDir)) return "nitro"; | ||
| } | ||
| const tsc = nitro.options.typescript.tsConfig?.compilerOptions; | ||
@@ -94,3 +24,3 @@ let config = { | ||
| plugins: [ | ||
| ...baseBuildPlugins(nitro, base), | ||
| ...await baseBuildPlugins(nitro, base), | ||
| oxc({ | ||
@@ -118,4 +48,2 @@ sourcemap: !!nitro.options.sourcemap, | ||
| rootDir: nitro.options.rootDir, | ||
| modulePaths: nitro.options.nodeModulesDirs, | ||
| mainFields: ["main"], | ||
| exportConditions: nitro.options.exportConditions | ||
@@ -128,7 +56,3 @@ }), | ||
| onwarn(warning, rollupWarn) { | ||
| if (![ | ||
| "EVAL", | ||
| "CIRCULAR_DEPENDENCY", | ||
| "THIS_IS_UNDEFINED" | ||
| ].includes(warning.code || "") && !warning.message.includes("Unsupported source map comment")) rollupWarn(warning); | ||
| if (!base.ignoreWarningCodes.has(warning.code || "")) rollupWarn(warning); | ||
| }, | ||
@@ -139,26 +63,13 @@ treeshake: { moduleSideEffects(id) { | ||
| output: { | ||
| format: "esm", | ||
| entryFileNames: "index.mjs", | ||
| chunkFileNames: (chunk) => getChunkName(chunk, nitro), | ||
| dir: nitro.options.output.serverDir, | ||
| entryFileNames: "index.mjs", | ||
| chunkFileNames(chunk) { | ||
| const id = normalize(chunk.moduleIds.at(-1) || ""); | ||
| for (const [dir, name] of chunkNamePrefixes) if (id.startsWith(dir)) return `chunks/${name}/[name].mjs`; | ||
| const routeHandler = nitro.options.handlers.find((h) => id.startsWith(h.handler)) || nitro.scannedHandlers.find((h) => id.startsWith(h.handler)); | ||
| if (routeHandler?.route) return `chunks/routes${routeHandler.route.replace(/:([^/]+)/g, "_$1").replace(/\/[^/]+$/g, "") || "/"}/[name].mjs`; | ||
| if (Object.entries(nitro.options.tasks).find(([_, task]) => task.handler === id)) return `chunks/tasks/[name].mjs`; | ||
| return `chunks/_/[name].mjs`; | ||
| }, | ||
| manualChunks(id) { | ||
| return getChunkGroup(id); | ||
| }, | ||
| inlineDynamicImports: nitro.options.inlineDynamicImports, | ||
| format: "esm", | ||
| exports: "auto", | ||
| intro: "", | ||
| outro: "", | ||
| generatedCode: { constBindings: true }, | ||
| sanitizeFileName: sanitizeFilePath, | ||
| sourcemap: nitro.options.sourcemap, | ||
| sourcemapExcludeSources: true, | ||
| sourcemapIgnoreList(relativePath) { | ||
| return relativePath.includes("node_modules"); | ||
| sourcemapIgnoreList: (id) => id.includes("node_modules"), | ||
| manualChunks(id) { | ||
| if (NODE_MODULES_RE.test(id)) return libChunkName(id); | ||
| } | ||
@@ -168,3 +79,4 @@ } | ||
| config = defu(nitro.options.rollupConfig, config); | ||
| if (config.output.inlineDynamicImports) delete config.output.manualChunks; | ||
| const outputConfig = config.output; | ||
| if (outputConfig.inlineDynamicImports || outputConfig.format === "iife") delete outputConfig.manualChunks; | ||
| return config; | ||
@@ -219,3 +131,3 @@ }; | ||
| ]); | ||
| const scanDirsWatcher = watch$1(scanDirs, { ignoreInitial: true }).on("all", (event, path, stat) => { | ||
| const scanDirsWatcher = watch$1(scanDirs, { ignoreInitial: true }).on("all", (event, path, stat$1) => { | ||
| if (watchReloadEvents.has(event)) reload(); | ||
@@ -289,3 +201,3 @@ }); | ||
| await nitro.hooks.callHook("build:before", nitro); | ||
| const config = getRollupConfig(nitro); | ||
| const config = await getRollupConfig(nitro); | ||
| await nitro.hooks.callHook("rollup:before", nitro, config); | ||
@@ -292,0 +204,0 @@ return nitro.options.dev ? watchDev(nitro, config) : buildProduction(nitro, config); |
@@ -1,43 +0,3 @@ | ||
| import "../_libs/c12.mjs"; | ||
| import "../_libs/gen-mapping.mjs"; | ||
| import "../_libs/magic-string.mjs"; | ||
| import "../_libs/acorn.mjs"; | ||
| import "../_libs/confbox.mjs"; | ||
| import "../_libs/local-pkg.mjs"; | ||
| import "../_libs/js-tokens.mjs"; | ||
| import "../_libs/strip-literal.mjs"; | ||
| import "../_libs/unimport.mjs"; | ||
| import "../_libs/picomatch.mjs"; | ||
| import "../_libs/fdir.mjs"; | ||
| import "../_libs/tinyglobby.mjs"; | ||
| import "../_libs/compatx.mjs"; | ||
| import "../_libs/klona.mjs"; | ||
| import { r as a } from "../_libs/std-env.mjs"; | ||
| import "../_chunks/B-D1JOIz.mjs"; | ||
| import "../_libs/escape-string-regexp.mjs"; | ||
| import "../_libs/tsconfck.mjs"; | ||
| import "../_libs/dot-prop.mjs"; | ||
| import "../_chunks/C7CbzoI1.mjs"; | ||
| import "../_chunks/ANM1K1bE.mjs"; | ||
| import "../_libs/rou3.mjs"; | ||
| import "../_libs/mime.mjs"; | ||
| import "../_libs/pathe.mjs"; | ||
| import "../_libs/untyped.mjs"; | ||
| import "../_libs/knitwork.mjs"; | ||
| import "./common.mjs"; | ||
| import "../_libs/httpxy.mjs"; | ||
| import "../_dev.mjs"; | ||
| import "../_libs/chokidar.mjs"; | ||
| import "../_libs/ultrahtml.mjs"; | ||
| import "../_libs/plugin-alias.mjs"; | ||
| import "../_libs/estree-walker.mjs"; | ||
| import "../_libs/plugin-commonjs.mjs"; | ||
| import "../_libs/plugin-inject.mjs"; | ||
| import "./common2.mjs"; | ||
| import "../_libs/remapping.mjs"; | ||
| import "../_libs/unwasm.mjs"; | ||
| import "../_libs/plugin-replace.mjs"; | ||
| import "../_libs/etag.mjs"; | ||
| import { t as nitro } from "./vite.plugin.mjs"; | ||
| import "../_libs/vite-plugin-fullstack.mjs"; | ||
| import { V as a } from "./common.mjs"; | ||
| import { nitro } from "nitro/vite"; | ||
@@ -47,3 +7,3 @@ //#region src/build/vite/build.ts | ||
| if (nitro$1.options.dev) throw new Error("Nitro dev CLI does not supports vite. Please use `vite dev` instead."); | ||
| const { createBuilder } = nitro$1.options.builder === "rolldown-vite" ? await import("rolldown-vite").catch(() => import("vite")) : await import("vite"); | ||
| const { createBuilder } = await import(nitro$1.options.__vitePkg__ || "vite"); | ||
| await (await createBuilder({ | ||
@@ -50,0 +10,0 @@ base: nitro$1.options.rootDir, |
+140
-110
@@ -1,24 +0,4 @@ | ||
| import consola$1 from "consola"; | ||
| import { colors } from "consola/utils"; | ||
| import { parseArgs } from "node:util"; | ||
| //#region node_modules/.pnpm/citty@0.1.6/node_modules/citty/dist/index.mjs | ||
| function toArray(val) { | ||
| if (Array.isArray(val)) return val; | ||
| return val === void 0 ? [] : [val]; | ||
| } | ||
| function formatLineColumns(lines, linePrefix = "") { | ||
| const maxLengh = []; | ||
| for (const line of lines) for (const [i, element] of line.entries()) maxLengh[i] = Math.max(maxLengh[i] || 0, element.length); | ||
| return lines.map((l) => l.map((c, i) => linePrefix + c[i === 0 ? "padStart" : "padEnd"](maxLengh[i])).join(" ")).join("\n"); | ||
| } | ||
| function resolveValue(input) { | ||
| return typeof input === "function" ? input() : input; | ||
| } | ||
| var CLIError = class extends Error { | ||
| constructor(message, code) { | ||
| super(message); | ||
| this.code = code; | ||
| this.name = "CLIError"; | ||
| } | ||
| }; | ||
| //#region node_modules/.pnpm/citty@0.2.0/node_modules/citty/dist/_chunks/libs/scule.mjs | ||
| const NUMBER_CHAR_RE = /\d/; | ||
@@ -88,87 +68,114 @@ const STR_SPLITTERS = [ | ||
| } | ||
| function toArr(any) { | ||
| return any == void 0 ? [] : Array.isArray(any) ? any : [any]; | ||
| //#endregion | ||
| //#region node_modules/.pnpm/citty@0.2.0/node_modules/citty/dist/index.mjs | ||
| function toArray(val) { | ||
| if (Array.isArray(val)) return val; | ||
| return val === void 0 ? [] : [val]; | ||
| } | ||
| function toVal(out, key, val, opts) { | ||
| let x; | ||
| const old = out[key]; | ||
| const nxt = ~opts.string.indexOf(key) ? val == void 0 || val === true ? "" : String(val) : typeof val === "boolean" ? val : ~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val; | ||
| out[key] = old == void 0 ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt]; | ||
| function formatLineColumns(lines, linePrefix = "") { | ||
| const maxLength = []; | ||
| for (const line of lines) for (const [i, element] of line.entries()) maxLength[i] = Math.max(maxLength[i] || 0, element.length); | ||
| return lines.map((l) => l.map((c, i) => linePrefix + c[i === 0 ? "padStart" : "padEnd"](maxLength[i])).join(" ")).join("\n"); | ||
| } | ||
| function resolveValue(input) { | ||
| return typeof input === "function" ? input() : input; | ||
| } | ||
| var CLIError = class extends Error { | ||
| code; | ||
| constructor(message, code) { | ||
| super(message); | ||
| this.name = "CLIError"; | ||
| this.code = code; | ||
| } | ||
| }; | ||
| function parseRawArgs(args = [], opts = {}) { | ||
| let k; | ||
| let arr; | ||
| let arg; | ||
| let name; | ||
| let val; | ||
| const out = { _: [] }; | ||
| let i = 0; | ||
| let j = 0; | ||
| let idx = 0; | ||
| const len = args.length; | ||
| const alibi = opts.alias !== void 0; | ||
| const strict = opts.unknown !== void 0; | ||
| const defaults = opts.default !== void 0; | ||
| opts.alias = opts.alias || {}; | ||
| opts.string = toArr(opts.string); | ||
| opts.boolean = toArr(opts.boolean); | ||
| if (alibi) for (k in opts.alias) { | ||
| arr = opts.alias[k] = toArr(opts.alias[k]); | ||
| for (i = 0; i < arr.length; i++) (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1); | ||
| const booleans = new Set(opts.boolean || []); | ||
| const strings = new Set(opts.string || []); | ||
| const aliasMap = opts.alias || {}; | ||
| const defaults = opts.default || {}; | ||
| const aliasToMain = /* @__PURE__ */ new Map(); | ||
| const mainToAliases = /* @__PURE__ */ new Map(); | ||
| for (const [key, value] of Object.entries(aliasMap)) { | ||
| const targets = value; | ||
| for (const target of targets) { | ||
| aliasToMain.set(key, target); | ||
| if (!mainToAliases.has(target)) mainToAliases.set(target, []); | ||
| mainToAliases.get(target).push(key); | ||
| aliasToMain.set(target, key); | ||
| if (!mainToAliases.has(key)) mainToAliases.set(key, []); | ||
| mainToAliases.get(key).push(target); | ||
| } | ||
| } | ||
| for (i = opts.boolean.length; i-- > 0;) { | ||
| arr = opts.alias[opts.boolean[i]] || []; | ||
| for (j = arr.length; j-- > 0;) opts.boolean.push(arr[j]); | ||
| const options = {}; | ||
| function getType(name) { | ||
| if (booleans.has(name)) return "boolean"; | ||
| const aliases = mainToAliases.get(name) || []; | ||
| for (const alias of aliases) if (booleans.has(alias)) return "boolean"; | ||
| return "string"; | ||
| } | ||
| for (i = opts.string.length; i-- > 0;) { | ||
| arr = opts.alias[opts.string[i]] || []; | ||
| for (j = arr.length; j-- > 0;) opts.string.push(arr[j]); | ||
| } | ||
| if (defaults) for (k in opts.default) { | ||
| name = typeof opts.default[k]; | ||
| arr = opts.alias[k] = opts.alias[k] || []; | ||
| if (opts[name] !== void 0) { | ||
| opts[name].push(k); | ||
| for (i = 0; i < arr.length; i++) opts[name].push(arr[i]); | ||
| } | ||
| } | ||
| const keys = strict ? Object.keys(opts.alias) : []; | ||
| for (i = 0; i < len; i++) { | ||
| arg = args[i]; | ||
| const allOptions = new Set([ | ||
| ...booleans, | ||
| ...strings, | ||
| ...Object.keys(aliasMap), | ||
| ...Object.values(aliasMap).flat(), | ||
| ...Object.keys(defaults) | ||
| ]); | ||
| for (const name of allOptions) if (!options[name]) options[name] = { | ||
| type: getType(name), | ||
| default: defaults[name] | ||
| }; | ||
| for (const [alias, main] of aliasToMain.entries()) if (alias.length === 1 && options[main] && !options[main].short) options[main].short = alias; | ||
| const processedArgs = []; | ||
| const negatedFlags = {}; | ||
| for (let i = 0; i < args.length; i++) { | ||
| const arg = args[i]; | ||
| if (arg === "--") { | ||
| out._ = out._.concat(args.slice(++i)); | ||
| processedArgs.push(...args.slice(i)); | ||
| break; | ||
| } | ||
| for (j = 0; j < arg.length; j++) if (arg.charCodeAt(j) !== 45) break; | ||
| if (j === 0) out._.push(arg); | ||
| else if (arg.substring(j, j + 3) === "no-") { | ||
| name = arg.slice(Math.max(0, j + 3)); | ||
| if (strict && !~keys.indexOf(name)) return opts.unknown(arg); | ||
| out[name] = false; | ||
| } else { | ||
| for (idx = j + 1; idx < arg.length; idx++) if (arg.charCodeAt(idx) === 61) break; | ||
| name = arg.substring(j, idx); | ||
| val = arg.slice(Math.max(0, ++idx)) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i]; | ||
| arr = j === 2 ? [name] : name; | ||
| for (idx = 0; idx < arr.length; idx++) { | ||
| name = arr[idx]; | ||
| if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name); | ||
| toVal(out, name, idx + 1 < arr.length || val, opts); | ||
| } | ||
| if (arg.startsWith("--no-")) { | ||
| const flagName = arg.slice(5); | ||
| negatedFlags[flagName] = true; | ||
| continue; | ||
| } | ||
| processedArgs.push(arg); | ||
| } | ||
| if (defaults) { | ||
| for (k in opts.default) if (out[k] === void 0) out[k] = opts.default[k]; | ||
| let parsed; | ||
| try { | ||
| parsed = parseArgs({ | ||
| args: processedArgs, | ||
| options: Object.keys(options).length > 0 ? options : void 0, | ||
| allowPositionals: true, | ||
| strict: false | ||
| }); | ||
| } catch { | ||
| parsed = { | ||
| values: {}, | ||
| positionals: processedArgs | ||
| }; | ||
| } | ||
| if (alibi) for (k in out) { | ||
| arr = opts.alias[k] || []; | ||
| while (arr.length > 0) out[arr.shift()] = out[k]; | ||
| const out = { _: [] }; | ||
| out._ = parsed.positionals; | ||
| for (const [key, value] of Object.entries(parsed.values)) out[key] = value; | ||
| for (const [name] of Object.entries(negatedFlags)) out[name] = false; | ||
| for (const [alias, main] of aliasToMain.entries()) { | ||
| if (out[alias] !== void 0 && out[main] === void 0) out[main] = out[alias]; | ||
| if (out[main] !== void 0 && out[alias] === void 0) out[alias] = out[main]; | ||
| } | ||
| return out; | ||
| } | ||
| function parseArgs(rawArgs, argsDef) { | ||
| const noColor = /* @__PURE__ */ (() => { | ||
| const env = globalThis.process?.env ?? {}; | ||
| return env.NO_COLOR === "1" || env.TERM === "dumb" || env.TEST || env.CI; | ||
| })(); | ||
| const _c = (c, r = 39) => (t) => noColor ? t : `\u001B[${c}m${t}\u001B[${r}m`; | ||
| const bold = /* @__PURE__ */ _c(1, 22); | ||
| const cyan = /* @__PURE__ */ _c(36); | ||
| const gray = /* @__PURE__ */ _c(90); | ||
| const underline = /* @__PURE__ */ _c(4, 24); | ||
| function parseArgs$1(rawArgs, argsDef) { | ||
| const parseOptions = { | ||
| boolean: [], | ||
| string: [], | ||
| mixed: [], | ||
| alias: {}, | ||
@@ -180,6 +187,14 @@ default: {} | ||
| if (arg.type === "positional") continue; | ||
| if (arg.type === "string") parseOptions.string.push(arg.name); | ||
| if (arg.type === "string" || arg.type === "enum") parseOptions.string.push(arg.name); | ||
| else if (arg.type === "boolean") parseOptions.boolean.push(arg.name); | ||
| if (arg.default !== void 0) parseOptions.default[arg.name] = arg.default; | ||
| if (arg.alias) parseOptions.alias[arg.name] = arg.alias; | ||
| const camelName = camelCase(arg.name); | ||
| const kebabName = kebabCase(arg.name); | ||
| if (camelName !== arg.name || kebabName !== arg.name) { | ||
| const existingAliases = toArray(parseOptions.alias[arg.name] || []); | ||
| if (camelName !== arg.name && !existingAliases.includes(camelName)) existingAliases.push(camelName); | ||
| if (kebabName !== arg.name && !existingAliases.includes(kebabName)) existingAliases.push(kebabName); | ||
| if (existingAliases.length > 0) parseOptions.alias[arg.name] = existingAliases; | ||
| } | ||
| } | ||
@@ -196,2 +211,6 @@ const parsed = parseRawArgs(rawArgs, parseOptions); | ||
| else parsedArgsProxy[arg.name] = arg.default; | ||
| } else if (arg.type === "enum") { | ||
| const argument = parsedArgsProxy[arg.name]; | ||
| const options = arg.options || []; | ||
| if (argument !== void 0 && options.length > 0 && !options.includes(argument)) throw new CLIError(`Invalid value for argument: ${cyan(`--${arg.name}`)} (${cyan(argument)}). Expected one of: ${options.map((o) => cyan(o)).join(", ")}.`, "EARG"); | ||
| } else if (arg.required && parsedArgsProxy[arg.name] === void 0) throw new CLIError(`Missing required argument: --${arg.name}`, "EARG"); | ||
@@ -214,3 +233,3 @@ return parsedArgsProxy; | ||
| const cmdArgs = await resolveValue(cmd.args || {}); | ||
| const parsedArgs = parseArgs(opts.rawArgs, cmdArgs); | ||
| const parsedArgs = parseArgs$1(opts.rawArgs, cmdArgs); | ||
| const context = { | ||
@@ -230,3 +249,3 @@ rawArgs: opts.rawArgs, | ||
| if (subCommandName) { | ||
| if (!subCommands[subCommandName]) throw new CLIError(`Unknown command \`${subCommandName}\``, "E_UNKNOWN_COMMAND"); | ||
| if (!subCommands[subCommandName]) throw new CLIError(`Unknown command ${cyan(subCommandName)}`, "E_UNKNOWN_COMMAND"); | ||
| const subCommand = await resolveValue(subCommands[subCommandName]); | ||
@@ -254,7 +273,8 @@ if (subCommand) await runCommand(subCommand, { rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1) }); | ||
| try { | ||
| consola$1.log(await renderUsage(cmd, parent) + "\n"); | ||
| console.log(await renderUsage(cmd, parent) + "\n"); | ||
| } catch (error) { | ||
| consola$1.error(error); | ||
| console.error(error); | ||
| } | ||
| } | ||
| const negativePrefixRe = /^no[-A-Z]/; | ||
| async function renderUsage(cmd, parent) { | ||
@@ -274,3 +294,3 @@ const cmdMeta = await resolveValue(cmd.meta || {}); | ||
| posLines.push([ | ||
| "`" + name + defaultHint + "`", | ||
| cyan(name + defaultHint), | ||
| arg.description || "", | ||
@@ -282,4 +302,13 @@ arg.valueHint ? `<${arg.valueHint}>` : "" | ||
| const isRequired = arg.required === true && arg.default === void 0; | ||
| const argStr = (arg.type === "boolean" && arg.default === true ? [...(arg.alias || []).map((a) => `--no-${a}`), `--no-${arg.name}`].join(", ") : [...(arg.alias || []).map((a) => `-${a}`), `--${arg.name}`].join(", ")) + (arg.type === "string" && (arg.valueHint || arg.default) ? `=${arg.valueHint ? `<${arg.valueHint}>` : `"${arg.default || ""}"`}` : ""); | ||
| argLines.push(["`" + argStr + (isRequired ? " (required)" : "") + "`", arg.description || ""]); | ||
| const argStr = [...(arg.alias || []).map((a) => `-${a}`), `--${arg.name}`].join(", ") + (arg.type === "string" && (arg.valueHint || arg.default) ? `=${arg.valueHint ? `<${arg.valueHint}>` : `"${arg.default || ""}"`}` : "") + (arg.type === "enum" && arg.options ? `=<${arg.options.join("|")}>` : ""); | ||
| argLines.push([cyan(argStr + (isRequired ? " (required)" : "")), arg.description || ""]); | ||
| /** | ||
| * print negative boolean arg variant usage when | ||
| * - enabled by default or has `negativeDescription` | ||
| * - not prefixed with `no-` or `no[A-Z]` | ||
| */ | ||
| if (arg.type === "boolean" && (arg.default === true || arg.negativeDescription) && !negativePrefixRe.test(arg.name)) { | ||
| const negativeArgStr = [...(arg.alias || []).map((a) => `--no-${a}`), `--no-${arg.name}`].join(", "); | ||
| argLines.push([cyan(negativeArgStr + (isRequired ? " (required)" : "")), arg.negativeDescription || ""]); | ||
| } | ||
| if (isRequired) usageLine.push(argStr); | ||
@@ -292,3 +321,4 @@ } | ||
| const meta = await resolveValue((await resolveValue(sub))?.meta); | ||
| commandsLines.push([`\`${name}\``, meta?.description || ""]); | ||
| if (meta?.hidden) continue; | ||
| commandsLines.push([cyan(name), meta?.description || ""]); | ||
| commandNames.push(name); | ||
@@ -300,7 +330,7 @@ } | ||
| const version = cmdMeta.version || parentMeta.version; | ||
| usageLines.push(colors.gray(`${cmdMeta.description} (${commandName + (version ? ` v${version}` : "")})`), ""); | ||
| usageLines.push(gray(`${cmdMeta.description} (${commandName + (version ? ` v${version}` : "")})`), ""); | ||
| const hasOptions = argLines.length > 0 || posLines.length > 0; | ||
| usageLines.push(`${colors.underline(colors.bold("USAGE"))} \`${commandName}${hasOptions ? " [OPTIONS]" : ""} ${usageLine.join(" ")}\``, ""); | ||
| usageLines.push(`${underline(bold("USAGE"))} ${cyan(`${commandName}${hasOptions ? " [OPTIONS]" : ""} ${usageLine.join(" ")}`)}`, ""); | ||
| if (posLines.length > 0) { | ||
| usageLines.push(colors.underline(colors.bold("ARGUMENTS")), ""); | ||
| usageLines.push(underline(bold("ARGUMENTS")), ""); | ||
| usageLines.push(formatLineColumns(posLines, " ")); | ||
@@ -310,3 +340,3 @@ usageLines.push(""); | ||
| if (argLines.length > 0) { | ||
| usageLines.push(colors.underline(colors.bold("OPTIONS")), ""); | ||
| usageLines.push(underline(bold("OPTIONS")), ""); | ||
| usageLines.push(formatLineColumns(argLines, " ")); | ||
@@ -316,5 +346,5 @@ usageLines.push(""); | ||
| if (commandsLines.length > 0) { | ||
| usageLines.push(colors.underline(colors.bold("COMMANDS")), ""); | ||
| usageLines.push(underline(bold("COMMANDS")), ""); | ||
| usageLines.push(formatLineColumns(commandsLines, " ")); | ||
| usageLines.push("", `Use \`${commandName} <command> --help\` for more information about a command.`); | ||
| usageLines.push("", `Use ${cyan(`${commandName} <command> --help`)} for more information about a command.`); | ||
| } | ||
@@ -333,9 +363,9 @@ return usageLines.filter((l) => typeof l === "string").join("\n"); | ||
| if (!meta?.version) throw new CLIError("No version specified", "E_NO_VERSION"); | ||
| consola$1.log(meta.version); | ||
| console.log(meta.version); | ||
| } else await runCommand(cmd, { rawArgs }); | ||
| } catch (error) { | ||
| const isCLIError = error instanceof CLIError; | ||
| if (!isCLIError) consola$1.error(error, "\n"); | ||
| if (isCLIError) await showUsage$1(...await resolveSubCommand(cmd, rawArgs)); | ||
| consola$1.error(error.message); | ||
| if (error instanceof CLIError) { | ||
| await showUsage$1(...await resolveSubCommand(cmd, rawArgs)); | ||
| console.error(error.message); | ||
| } else console.error(error, "\n"); | ||
| process.exit(1); | ||
@@ -342,0 +372,0 @@ } |
@@ -1,144 +0,1 @@ | ||
| //#region node_modules/.pnpm/estree-walker@2.0.2/node_modules/estree-walker/dist/esm/estree-walker.js | ||
| /** @typedef { import('estree').BaseNode} BaseNode */ | ||
| /** @typedef {{ | ||
| skip: () => void; | ||
| remove: () => void; | ||
| replace: (node: BaseNode) => void; | ||
| }} WalkerContext */ | ||
| var WalkerBase$1 = class { | ||
| constructor() { | ||
| /** @type {boolean} */ | ||
| this.should_skip = false; | ||
| /** @type {boolean} */ | ||
| this.should_remove = false; | ||
| /** @type {BaseNode | null} */ | ||
| this.replacement = null; | ||
| /** @type {WalkerContext} */ | ||
| this.context = { | ||
| skip: () => this.should_skip = true, | ||
| remove: () => this.should_remove = true, | ||
| replace: (node) => this.replacement = node | ||
| }; | ||
| } | ||
| /** | ||
| * | ||
| * @param {any} parent | ||
| * @param {string} prop | ||
| * @param {number} index | ||
| * @param {BaseNode} node | ||
| */ | ||
| replace(parent, prop, index, node) { | ||
| if (parent) if (index !== null) parent[prop][index] = node; | ||
| else parent[prop] = node; | ||
| } | ||
| /** | ||
| * | ||
| * @param {any} parent | ||
| * @param {string} prop | ||
| * @param {number} index | ||
| */ | ||
| remove(parent, prop, index) { | ||
| if (parent) if (index !== null) parent[prop].splice(index, 1); | ||
| else delete parent[prop]; | ||
| } | ||
| }; | ||
| /** @typedef { import('estree').BaseNode} BaseNode */ | ||
| /** @typedef { import('./walker.js').WalkerContext} WalkerContext */ | ||
| /** @typedef {( | ||
| * this: WalkerContext, | ||
| * node: BaseNode, | ||
| * parent: BaseNode, | ||
| * key: string, | ||
| * index: number | ||
| * ) => void} SyncHandler */ | ||
| var SyncWalker$1 = class extends WalkerBase$1 { | ||
| /** | ||
| * | ||
| * @param {SyncHandler} enter | ||
| * @param {SyncHandler} leave | ||
| */ | ||
| constructor(enter, leave) { | ||
| super(); | ||
| /** @type {SyncHandler} */ | ||
| this.enter = enter; | ||
| /** @type {SyncHandler} */ | ||
| this.leave = leave; | ||
| } | ||
| /** | ||
| * | ||
| * @param {BaseNode} node | ||
| * @param {BaseNode} parent | ||
| * @param {string} [prop] | ||
| * @param {number} [index] | ||
| * @returns {BaseNode} | ||
| */ | ||
| visit(node, parent, prop, index) { | ||
| if (node) { | ||
| if (this.enter) { | ||
| const _should_skip = this.should_skip; | ||
| const _should_remove = this.should_remove; | ||
| const _replacement = this.replacement; | ||
| this.should_skip = false; | ||
| this.should_remove = false; | ||
| this.replacement = null; | ||
| this.enter.call(this.context, node, parent, prop, index); | ||
| if (this.replacement) { | ||
| node = this.replacement; | ||
| this.replace(parent, prop, index, node); | ||
| } | ||
| if (this.should_remove) this.remove(parent, prop, index); | ||
| const skipped = this.should_skip; | ||
| const removed = this.should_remove; | ||
| this.should_skip = _should_skip; | ||
| this.should_remove = _should_remove; | ||
| this.replacement = _replacement; | ||
| if (skipped) return node; | ||
| if (removed) return null; | ||
| } | ||
| for (const key in node) { | ||
| const value = node[key]; | ||
| if (typeof value !== "object") continue; | ||
| else if (Array.isArray(value)) { | ||
| for (let i = 0; i < value.length; i += 1) if (value[i] !== null && typeof value[i].type === "string") { | ||
| if (!this.visit(value[i], node, key, i)) i--; | ||
| } | ||
| } else if (value !== null && typeof value.type === "string") this.visit(value, node, key, null); | ||
| } | ||
| if (this.leave) { | ||
| const _replacement = this.replacement; | ||
| const _should_remove = this.should_remove; | ||
| this.replacement = null; | ||
| this.should_remove = false; | ||
| this.leave.call(this.context, node, parent, prop, index); | ||
| if (this.replacement) { | ||
| node = this.replacement; | ||
| this.replace(parent, prop, index, node); | ||
| } | ||
| if (this.should_remove) this.remove(parent, prop, index); | ||
| const removed = this.should_remove; | ||
| this.replacement = _replacement; | ||
| this.should_remove = _should_remove; | ||
| if (removed) return null; | ||
| } | ||
| } | ||
| return node; | ||
| } | ||
| }; | ||
| /** @typedef { import('estree').BaseNode} BaseNode */ | ||
| /** @typedef { import('./sync.js').SyncHandler} SyncHandler */ | ||
| /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */ | ||
| /** | ||
| * | ||
| * @param {BaseNode} ast | ||
| * @param {{ | ||
| * enter?: SyncHandler | ||
| * leave?: SyncHandler | ||
| * }} walker | ||
| * @returns {BaseNode} | ||
| */ | ||
| function walk$1(ast, { enter, leave }) { | ||
| return new SyncWalker$1(enter, leave).visit(ast, null); | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js | ||
@@ -330,2 +187,2 @@ /** | ||
| //#endregion | ||
| export { walk$1 as n, walk as t }; | ||
| export { walk as t }; |
@@ -0,1 +1,2 @@ | ||
| import { n as __exportAll } from "../_common.mjs"; | ||
| import http from "node:http"; | ||
@@ -6,2 +7,6 @@ import https from "node:https"; | ||
| //#region node_modules/.pnpm/httpxy@0.1.7/node_modules/httpxy/dist/index.mjs | ||
| var dist_exports = /* @__PURE__ */ __exportAll({ | ||
| ProxyServer: () => ProxyServer, | ||
| createProxyServer: () => createProxyServer | ||
| }); | ||
| const upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i; | ||
@@ -411,2 +416,2 @@ const isSSL = /^https|wss/; | ||
| //#endregion | ||
| export { createProxyServer as n, ProxyServer as t }; | ||
| export { dist_exports as n, createProxyServer as t }; |
@@ -0,4 +1,6 @@ | ||
| import { n as __exportAll } from "../_common.mjs"; | ||
| import path from "node:path"; | ||
| //#region node_modules/.pnpm/@rollup+plugin-alias@6.0.0_rollup@4.53.2/node_modules/@rollup/plugin-alias/dist/index.js | ||
| //#region node_modules/.pnpm/@rollup+plugin-alias@6.0.0_rollup@4.55.3/node_modules/@rollup/plugin-alias/dist/index.js | ||
| var dist_exports = /* @__PURE__ */ __exportAll({ default: () => alias }); | ||
| function matches(pattern, importee) { | ||
@@ -64,2 +66,2 @@ if (pattern instanceof RegExp) return pattern.test(importee); | ||
| //#endregion | ||
| export { alias as t }; | ||
| export { dist_exports as n, alias as t }; |
@@ -1,7 +0,7 @@ | ||
| import { t as MagicString } from "./magic-string.mjs"; | ||
| import { n as walk } from "./estree-walker.mjs"; | ||
| import { a as makeLegalIdentifier, n as attachScopes, r as createFilter } from "./plugin-commonjs.mjs"; | ||
| import { n as __exportAll } from "../_common.mjs"; | ||
| import { S as MagicString, c as walk, i as createFilter, r as attachScopes, s as makeLegalIdentifier } from "../_build/common.mjs"; | ||
| import { sep } from "path"; | ||
| //#region node_modules/.pnpm/@rollup+plugin-inject@5.0.5_rollup@4.53.2/node_modules/@rollup/plugin-inject/dist/es/index.js | ||
| //#region node_modules/.pnpm/@rollup+plugin-inject@5.0.5_rollup@4.55.3/node_modules/@rollup/plugin-inject/dist/es/index.js | ||
| var es_exports = /* @__PURE__ */ __exportAll({ default: () => inject }); | ||
| var escape = function(str) { | ||
@@ -135,2 +135,2 @@ return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&"); | ||
| //#endregion | ||
| export { inject as t }; | ||
| export { inject as n, es_exports as t }; |
@@ -1,4 +0,4 @@ | ||
| import { i as dataToEsm, r as createFilter } from "./plugin-commonjs.mjs"; | ||
| import { a as dataToEsm, i as createFilter } from "../_build/common.mjs"; | ||
| //#region node_modules/.pnpm/@rollup+plugin-json@6.1.0_rollup@4.53.2/node_modules/@rollup/plugin-json/dist/es/index.js | ||
| //#region node_modules/.pnpm/@rollup+plugin-json@6.1.0_rollup@4.55.3/node_modules/@rollup/plugin-json/dist/es/index.js | ||
| function json(options) { | ||
@@ -5,0 +5,0 @@ if (options === void 0) options = {}; |
@@ -1,2 +0,2 @@ | ||
| import { a as toDecodedMap, c as decodedMappings, i as setSourceContent, l as traceSegment, n as maybeAddSegment, o as toEncodedMap, r as setIgnore, s as TraceMap, t as GenMapping } from "./gen-mapping.mjs"; | ||
| import { a as toDecodedMap, c as decodedMappings, i as setSourceContent, l as traceSegment, n as maybeAddSegment, o as toEncodedMap, r as setIgnore, s as TraceMap, t as GenMapping } from "./resolve-uri+gen-mapping.mjs"; | ||
@@ -3,0 +3,0 @@ //#region node_modules/.pnpm/@jridgewell+remapping@2.3.5/node_modules/@jridgewell/remapping/dist/remapping.mjs |
@@ -1,2 +0,2 @@ | ||
| //#region node_modules/.pnpm/rou3@0.7.10/node_modules/rou3/dist/index.mjs | ||
| //#region node_modules/.pnpm/rou3@0.7.12/node_modules/rou3/dist/index.mjs | ||
| const NullProtoObj = /* @__PURE__ */ (() => { | ||
@@ -22,3 +22,3 @@ const e = function() {}; | ||
| for (const [index, name] of paramsMap) { | ||
| const segment = index < 0 ? segments.slice(-1 * index).join("/") : segments[index]; | ||
| const segment = index < 0 ? segments.slice(-(index + 1)).join("/") : segments[index]; | ||
| if (typeof name === "string") params[name] = segment; | ||
@@ -38,2 +38,3 @@ else { | ||
| if (path.charCodeAt(0) !== 47) path = `/${path}`; | ||
| path = path.replace(/\\:/g, "%3A"); | ||
| const segments = splitPath(path); | ||
@@ -45,3 +46,3 @@ let node = ctx.root; | ||
| for (let i = 0; i < segments.length; i++) { | ||
| const segment = segments[i]; | ||
| let segment = segments[i]; | ||
| if (segment.startsWith("**")) { | ||
@@ -51,3 +52,3 @@ if (!node.wildcard) node.wildcard = { key: "**" }; | ||
| paramsMap.push([ | ||
| -i, | ||
| -(i + 1), | ||
| segment.split(":")[1] || "_", | ||
@@ -82,2 +83,4 @@ segment.length === 2 | ||
| } | ||
| if (segment === "\\*") segment = segments[i] = "*"; | ||
| else if (segment === "\\*\\*") segment = segments[i] = "**"; | ||
| const child = node.static?.[segment]; | ||
@@ -100,3 +103,3 @@ if (child) node = child; | ||
| }); | ||
| if (!hasParams) ctx.static[path] = node; | ||
| if (!hasParams) ctx.static["/" + segments.join("/")] = node; | ||
| } | ||
@@ -209,3 +212,3 @@ function getParamRegexp(segment) { | ||
| //#endregion | ||
| //#region node_modules/.pnpm/rou3@0.7.10/node_modules/rou3/dist/compiler.mjs | ||
| //#region node_modules/.pnpm/rou3@0.7.12/node_modules/rou3/dist/compiler.mjs | ||
| /** | ||
@@ -212,0 +215,0 @@ * Compile the router instance into a compact runnable code. |
@@ -0,3 +1,3 @@ | ||
| import fs, { promises } from "node:fs"; | ||
| import path from "node:path"; | ||
| import fs, { promises } from "node:fs"; | ||
| import { createRequire } from "module"; | ||
@@ -50,4 +50,4 @@ | ||
| if (cache && (cache.hasParseResult(tsconfig) || cache.hasParseResult(filename))) return tsconfig; | ||
| return promises.stat(tsconfig).then((stat) => { | ||
| if (stat.isFile() || stat.isFIFO()) return tsconfig; | ||
| return promises.stat(tsconfig).then((stat$1) => { | ||
| if (stat$1.isFile() || stat$1.isFIFO()) return tsconfig; | ||
| else throw new Error(`${filename} exists but is not a regular file.`); | ||
@@ -54,0 +54,0 @@ }); |
+130
-80
@@ -1,21 +0,15 @@ | ||
| import { O as relative$1, _ as h, c as findNearestFile, d as readGitConfig, f as readPackageJSON, h as resolveModulePath, k as resolve$1, s as findFile, w as join$1, x as dirname$1 } from "./_libs/c12.mjs"; | ||
| import "./_libs/acorn.mjs"; | ||
| import { n as gr, t as Q } from "./_libs/confbox.mjs"; | ||
| import { r as fileURLToPath } from "./_libs/local-pkg.mjs"; | ||
| import "./_libs/picomatch.mjs"; | ||
| import "./_libs/fdir.mjs"; | ||
| import { t as glob } from "./_libs/tinyglobby.mjs"; | ||
| import "./_common.mjs"; | ||
| import { $ as resolveModulePath, G as findFile, I as prettyPath$1, J as readGitConfig, K as findNearestFile, N as glob, R as writeFile$2, U as p, V as a, X as h, Y as readPackageJSON, at as join$1, ct as resolve$1, nt as dirname$1, st as relative$1, z as K } from "./_build/common.mjs"; | ||
| import { i as gr, n as Q } from "./_libs/confbox.mjs"; | ||
| import { r as resolveCompatibilityDatesFromEnv, t as formatCompatibilityDate } from "./_libs/compatx.mjs"; | ||
| import { a as p, r as a, t as K } from "./_libs/std-env.mjs"; | ||
| import "./_libs/dot-prop.mjs"; | ||
| import { i as writeFile$2 } from "./_chunks/C7CbzoI1.mjs"; | ||
| import { builtinModules } from "node:module"; | ||
| import consola$1 from "consola"; | ||
| import { dirname, extname, relative, resolve } from "node:path"; | ||
| import { kebabCase } from "scule"; | ||
| import { existsSync, promises } from "node:fs"; | ||
| import { hasProtocol, joinURL, withLeadingSlash, withTrailingSlash, withoutLeadingSlash } from "ufo"; | ||
| import fsp, { readFile, writeFile } from "node:fs/promises"; | ||
| import { dirname, extname, relative, resolve } from "node:path"; | ||
| import { defu } from "defu"; | ||
| import { hasProtocol, joinURL, withLeadingSlash, withTrailingSlash, withoutLeadingSlash } from "ufo"; | ||
| import { presetsDir, runtimeDir, version } from "nitro/meta"; | ||
| import { colors } from "consola/utils"; | ||
| import { kebabCase } from "scule"; | ||
@@ -82,3 +76,3 @@ //#region src/presets/_utils/preset.ts | ||
| //#region src/presets/_nitro/preset.ts | ||
| var preset_default = [ | ||
| var preset_default$26 = [ | ||
| ...base_worker_default, | ||
@@ -121,3 +115,3 @@ ...nitro_dev_default, | ||
| }); | ||
| var preset_default$1 = [ | ||
| var preset_default$25 = [ | ||
| _static, | ||
@@ -135,3 +129,3 @@ githubPages, | ||
| }, { name: "alwaysdata" }); | ||
| var preset_default$2 = [alwaysdata]; | ||
| var preset_default$24 = [alwaysdata]; | ||
@@ -205,2 +199,3 @@ //#endregion | ||
| entry: "./aws-amplify/runtime/aws-amplify", | ||
| manifest: { deploymentId: process.env.AWS_JOB_ID }, | ||
| serveStatic: true, | ||
@@ -220,3 +215,3 @@ output: { | ||
| }); | ||
| var preset_default$3 = [awsAmplify]; | ||
| var preset_default$23 = [awsAmplify]; | ||
@@ -232,3 +227,3 @@ //#endregion | ||
| }, { name: "aws-lambda" }); | ||
| var preset_default$4 = [awsLambda]; | ||
| var preset_default$22 = [awsLambda]; | ||
@@ -352,3 +347,3 @@ //#endregion | ||
| }); | ||
| var preset_default$5 = [azureSWA]; | ||
| var preset_default$21 = [azureSWA]; | ||
@@ -368,3 +363,3 @@ //#endregion | ||
| }, { name: "bun" }); | ||
| var preset_default$6 = [bun]; | ||
| var preset_default$20 = [bun]; | ||
@@ -380,3 +375,3 @@ //#endregion | ||
| }); | ||
| var preset_default$7 = [cleavr]; | ||
| var preset_default$19 = [cleavr]; | ||
@@ -439,3 +434,3 @@ //#endregion | ||
| //#region src/presets/cloudflare/unenv/preset.ts | ||
| const unencCfNodeCompat = { | ||
| const unenvCfNodeCompat = { | ||
| meta: { name: "nitro:cloudflare-node-compat" }, | ||
@@ -544,3 +539,3 @@ external: builtnNodeModules$1, | ||
| nitro.options.cloudflare.nodeCompat ??= true; | ||
| if (nitro.options.cloudflare.nodeCompat) nitro.options.unenv.push(unencCfNodeCompat); | ||
| if (nitro.options.cloudflare.nodeCompat) nitro.options.unenv.push(unenvCfNodeCompat); | ||
| } | ||
@@ -620,3 +615,3 @@ const extensionParsers = { | ||
| if (!await resolveModulePath("wrangler", { | ||
| from: nitro.options.nodeModulesDirs, | ||
| from: nitro.options.rootDir, | ||
| try: true | ||
@@ -649,4 +644,2 @@ })) { | ||
| }; | ||
| nitro.options.externals.inline = nitro.options.externals.inline || []; | ||
| nitro.options.externals.inline.push(fileURLToPath(new URL("runtime/", import.meta.url))); | ||
| nitro.options.plugins = nitro.options.plugins || []; | ||
@@ -660,2 +653,32 @@ nitro.options.plugins.unshift(resolveModulePath("./cloudflare/runtime/plugin.dev", { | ||
| //#endregion | ||
| //#region src/presets/cloudflare/entry-exports.ts | ||
| const RESOLVE_EXTENSIONS = [ | ||
| ".ts", | ||
| ".js", | ||
| ".mts", | ||
| ".mjs" | ||
| ]; | ||
| async function setupEntryExports(nitro) { | ||
| const exportsEntry = resolveExportsEntry(nitro); | ||
| if (!exportsEntry) return; | ||
| const originalEntry = nitro.options.entry; | ||
| const virtualEntryId = nitro.options.entry = "#nitro/virtual/cloudflare-server-entry"; | ||
| nitro.options.virtual[virtualEntryId] = ` | ||
| export * from "${exportsEntry}"; | ||
| export * from "${originalEntry}"; | ||
| export { default } from "${originalEntry}"; | ||
| `; | ||
| } | ||
| function resolveExportsEntry(nitro) { | ||
| const entry = resolveModulePath(nitro.options.cloudflare?.exports || "./exports.cloudflare.ts", { | ||
| from: nitro.options.rootDir, | ||
| extensions: RESOLVE_EXTENSIONS, | ||
| try: true | ||
| }); | ||
| if (!entry && nitro.options.cloudflare?.exports) nitro.logger.warn(`Your custom Cloudflare entrypoint \`${prettyPath$1(nitro.options.cloudflare.exports)}\` file does not exist.`); | ||
| else if (entry && !nitro.options.cloudflare?.exports) nitro.logger.info(`Detected \`${prettyPath$1(entry)}\` as Cloudflare entrypoint.`); | ||
| return entry; | ||
| } | ||
| //#endregion | ||
| //#region src/presets/cloudflare/preset.ts | ||
@@ -690,2 +713,3 @@ const cloudflarePages = defineNitroPreset({ | ||
| await enableNodeCompat(nitro); | ||
| await setupEntryExports(nitro); | ||
| }, | ||
@@ -758,2 +782,3 @@ async compiled(nitro) { | ||
| await enableNodeCompat(nitro); | ||
| await setupEntryExports(nitro); | ||
| }, | ||
@@ -778,3 +803,3 @@ async compiled(nitro) { | ||
| }, { name: "cloudflare-durable" }); | ||
| var preset_default$8 = [ | ||
| var preset_default$18 = [ | ||
| cloudflarePages, | ||
@@ -878,5 +903,5 @@ cloudflarePagesStatic, | ||
| entry: "./deno/runtime/deno-deploy", | ||
| manifest: { deploymentId: process.env.DENO_DEPLOYMENT_ID }, | ||
| exportConditions: ["deno"], | ||
| node: false, | ||
| noExternals: true, | ||
| serveStatic: "deno", | ||
@@ -904,3 +929,3 @@ commands: { | ||
| rollupConfig: { | ||
| external: (id) => id.startsWith("https://"), | ||
| external: (id) => id.startsWith("https://") || id.startsWith("node:") || builtinModules.includes(id), | ||
| output: { hoistTransitiveImports: false } | ||
@@ -915,3 +940,3 @@ }, | ||
| }); | ||
| var preset_default$9 = [denoDeploy, denoServer]; | ||
| var preset_default$17 = [denoDeploy, denoServer]; | ||
@@ -924,3 +949,3 @@ //#endregion | ||
| }, { name: "digital-ocean" }); | ||
| var preset_default$10 = [digitalOcean]; | ||
| var preset_default$16 = [digitalOcean]; | ||
@@ -953,3 +978,3 @@ //#endregion | ||
| }); | ||
| var preset_default$11 = [firebaseAppHosting]; | ||
| var preset_default$15 = [firebaseAppHosting]; | ||
@@ -962,3 +987,3 @@ //#endregion | ||
| }, { name: "flight-control" }); | ||
| var preset_default$12 = [flightControl]; | ||
| var preset_default$14 = [flightControl]; | ||
@@ -976,3 +1001,3 @@ //#endregion | ||
| }, { name: "heroku" }); | ||
| var preset_default$14 = [heroku]; | ||
| var preset_default$12 = [heroku]; | ||
@@ -1127,3 +1152,3 @@ //#endregion | ||
| }, { name: "iis-node" }); | ||
| var preset_default$15 = [iisHandler, iisNode]; | ||
| var preset_default$11 = [iisHandler, iisNode]; | ||
@@ -1136,3 +1161,3 @@ //#endregion | ||
| }, { name: "koyeb" }); | ||
| var preset_default$16 = [koyeb]; | ||
| var preset_default$10 = [koyeb]; | ||
@@ -1210,2 +1235,3 @@ //#endregion | ||
| entry: "./netlify/runtime/netlify", | ||
| manifest: { deploymentId: process.env.DEPLOY_ID }, | ||
| output: { | ||
@@ -1221,6 +1247,10 @@ dir: "{{ rootDir }}/.netlify/functions-internal", | ||
| await promises.writeFile(join$1(nitro.options.output.dir, "server", "server.mjs"), generateNetlifyFunction(nitro)); | ||
| if (nitro.options.netlify) { | ||
| if (nitro.options.netlify?.images) { | ||
| nitro.options.netlify.config ||= {}; | ||
| nitro.options.netlify.config.images ||= nitro.options.netlify?.images; | ||
| } | ||
| if (Object.keys(nitro.options.netlify?.config || {}).length > 0) { | ||
| const configPath = join$1(nitro.options.output.dir, "../deploy/v1/config.json"); | ||
| await promises.mkdir(dirname$1(configPath), { recursive: true }); | ||
| await promises.writeFile(configPath, JSON.stringify(nitro.options.netlify), "utf8"); | ||
| await promises.writeFile(configPath, JSON.stringify(nitro.options.netlify?.config), "utf8"); | ||
| } | ||
@@ -1235,2 +1265,3 @@ } } | ||
| entry: "./netlify/runtime/netlify-edge", | ||
| manifest: { deploymentId: process.env.DEPLOY_ID }, | ||
| exportConditions: ["netlify"], | ||
@@ -1267,2 +1298,3 @@ output: { | ||
| extends: "static", | ||
| manifest: { deploymentId: process.env.DEPLOY_ID }, | ||
| output: { | ||
@@ -1283,3 +1315,3 @@ dir: "{{ rootDir }}/dist", | ||
| }); | ||
| var preset_default$17 = [ | ||
| var preset_default$9 = [ | ||
| netlify, | ||
@@ -1335,3 +1367,3 @@ netlifyEdge, | ||
| const nodeMiddleware = defineNitroPreset({ entry: "./node/runtime/node-middleware" }, { name: "node-middleware" }); | ||
| var preset_default$18 = [ | ||
| var preset_default$8 = [ | ||
| nodeServer, | ||
@@ -1348,3 +1380,3 @@ nodeCluster, | ||
| }, { name: "platform-sh" }); | ||
| var preset_default$19 = [platformSh]; | ||
| var preset_default$7 = [platformSh]; | ||
@@ -1357,3 +1389,3 @@ //#endregion | ||
| }, { name: "render-com" }); | ||
| var preset_default$20 = [renderCom]; | ||
| var preset_default$6 = [renderCom]; | ||
@@ -1365,3 +1397,2 @@ //#endregion | ||
| serveStatic: false, | ||
| exportConditions: ["import", "default"], | ||
| output: { publicDir: "{{ output.dir }}/public/{{ baseURL }}" }, | ||
@@ -1377,3 +1408,3 @@ commands: { preview: "npx srvx --prod ./" }, | ||
| }, { name: "standard" }); | ||
| var preset_default$21 = [standard]; | ||
| var preset_default$5 = [standard]; | ||
@@ -1392,5 +1423,9 @@ //#endregion | ||
| }); | ||
| var preset_default$22 = [stormkit]; | ||
| var preset_default$4 = [stormkit]; | ||
| //#endregion | ||
| //#region src/presets/vercel/runtime/isr.ts | ||
| const ISR_URL_PARAM = "__isr_route"; | ||
| //#endregion | ||
| //#region src/presets/vercel/utils.ts | ||
@@ -1455,2 +1490,12 @@ const SUPPORTED_NODE_VERSIONS = [20, 22]; | ||
| }), | ||
| ...nitro.options.vercel?.skewProtection && nitro.options.manifest?.deploymentId ? [{ | ||
| src: "/.*", | ||
| has: [{ | ||
| type: "header", | ||
| key: "Sec-Fetch-Dest", | ||
| value: "document" | ||
| }], | ||
| headers: { "Set-Cookie": `__vdpl=${nitro.options.manifest.deploymentId}; Path=${nitro.options.baseURL}; SameSite=Strict; Secure; HttpOnly` }, | ||
| continue: true | ||
| }] : [], | ||
| ...nitro.options.publicAssets.filter((asset) => !asset.fallthrough).map((asset) => joinURL(nitro.options.baseURL, asset.baseURL || "/")).map((baseURL) => ({ | ||
@@ -1466,6 +1511,6 @@ src: baseURL + "(.*)", | ||
| config.routes.push(...nitro.options.routeRules["/"]?.isr ? [{ | ||
| src: "(?<url>/)", | ||
| dest: `/index${ISR_SUFFIX}?url=$url` | ||
| src: `(?<${ISR_URL_PARAM}>/)`, | ||
| dest: `/index${ISR_SUFFIX}?${ISR_URL_PARAM}=$${ISR_URL_PARAM}` | ||
| }] : [], ...rules.filter(([key, value]) => value.isr !== void 0 && key !== "/").map(([key, value]) => { | ||
| const src = key.replace(/^(.*)\/\*\*/, "(?<url>$1/.*)"); | ||
| const src = `(?<${ISR_URL_PARAM}>${normalizeRouteSrc(key)})`; | ||
| if (value.isr === false) return { | ||
@@ -1477,3 +1522,3 @@ src, | ||
| src, | ||
| dest: withLeadingSlash(normalizeRouteDest(key) + ISR_SUFFIX + "?url=$url") | ||
| dest: withLeadingSlash(normalizeRouteDest(key) + ISR_SUFFIX + `?${ISR_URL_PARAM}=$${ISR_URL_PARAM}`) | ||
| }; | ||
@@ -1578,2 +1623,3 @@ }), ...(o11Routes || []).map((route) => ({ | ||
| }; | ||
| if (prerenderConfig.allowQuery && !prerenderConfig.allowQuery.includes(ISR_URL_PARAM)) prerenderConfig.allowQuery.push(ISR_URL_PARAM); | ||
| await writeFile$1(filename, JSON.stringify(prerenderConfig, null, 2)); | ||
@@ -1586,2 +1632,4 @@ } | ||
| entry: "./vercel/runtime/vercel.{format}", | ||
| manifest: { deploymentId: process.env.VERCEL_DEPLOYMENT_ID }, | ||
| vercel: { skewProtection: !!process.env.VERCEL_SKEW_PROTECTION_ENABLED }, | ||
| output: { | ||
@@ -1593,3 +1641,3 @@ dir: "{{ rootDir }}/.vercel/output", | ||
| commands: { | ||
| preview: "", | ||
| preview: "npx srvx --static ../../static ./functions/__server.func/index.mjs", | ||
| deploy: "npx vercel deploy --prebuilt" | ||
@@ -1621,2 +1669,4 @@ }, | ||
| extends: "static", | ||
| manifest: { deploymentId: process.env.VERCEL_DEPLOYMENT_ID }, | ||
| vercel: { skewProtection: !!process.env.VERCEL_SKEW_PROTECTION_ENABLED }, | ||
| output: { | ||
@@ -1640,3 +1690,3 @@ dir: "{{ rootDir }}/.vercel/output", | ||
| }); | ||
| var preset_default$23 = [vercel, vercelStatic]; | ||
| var preset_default$3 = [vercel, vercelStatic]; | ||
@@ -1653,3 +1703,3 @@ //#endregion | ||
| }, { name: "winterjs" }); | ||
| var preset_default$24 = [winterjs]; | ||
| var preset_default$2 = [winterjs]; | ||
@@ -1696,3 +1746,3 @@ //#endregion | ||
| }); | ||
| var preset_default$25 = [zeabur, zeaburStatic]; | ||
| var preset_default$1 = [zeabur, zeaburStatic]; | ||
@@ -1715,3 +1765,3 @@ //#endregion | ||
| }); | ||
| var preset_default$26 = [zerops, zeropsStatic]; | ||
| var preset_default = [zerops, zeropsStatic]; | ||
@@ -1721,29 +1771,29 @@ //#endregion | ||
| var _all_gen_default = [ | ||
| ...preset_default, | ||
| ...preset_default$26, | ||
| ...preset_default$25, | ||
| ...preset_default$24, | ||
| ...preset_default$23, | ||
| ...preset_default$22, | ||
| ...preset_default$21, | ||
| ...preset_default$20, | ||
| ...preset_default$19, | ||
| ...preset_default$18, | ||
| ...preset_default$17, | ||
| ...preset_default$16, | ||
| ...preset_default$15, | ||
| ...preset_default$14, | ||
| ...preset_default$13, | ||
| ...preset_default$12, | ||
| ...preset_default$11, | ||
| ...preset_default$10, | ||
| ...preset_default$9, | ||
| ...preset_default$8, | ||
| ...preset_default$7, | ||
| ...preset_default$6, | ||
| ...preset_default$5, | ||
| ...preset_default$4, | ||
| ...preset_default$3, | ||
| ...preset_default$2, | ||
| ...preset_default$1, | ||
| ...preset_default$2, | ||
| ...preset_default$3, | ||
| ...preset_default$4, | ||
| ...preset_default$5, | ||
| ...preset_default$6, | ||
| ...preset_default$7, | ||
| ...preset_default$8, | ||
| ...preset_default$9, | ||
| ...preset_default$10, | ||
| ...preset_default$11, | ||
| ...preset_default$12, | ||
| ...preset_default$13, | ||
| ...preset_default$14, | ||
| ...preset_default$15, | ||
| ...preset_default$16, | ||
| ...preset_default$17, | ||
| ...preset_default$18, | ||
| ...preset_default$19, | ||
| ...preset_default$20, | ||
| ...preset_default$21, | ||
| ...preset_default$22, | ||
| ...preset_default$23, | ||
| ...preset_default$24, | ||
| ...preset_default$25, | ||
| ...preset_default$26 | ||
| ...preset_default | ||
| ]; | ||
@@ -1750,0 +1800,0 @@ |
@@ -5,3 +5,3 @@ import { t as NitroDevApp } from "./_dev.mjs"; | ||
| import { Server, ServerOptions } from "srvx"; | ||
| import { DevMessageListener, DevRPCHooks, LoadConfigOptions, Nitro, NitroBuildInfo, NitroConfig, NitroOptions, TaskEvent, TaskRunnerOptions } from "nitro/types"; | ||
| import { LoadConfigOptions, Nitro, NitroBuildInfo, NitroConfig, NitroOptions, RunnerMessageListener, RunnerRPCHooks, TaskEvent, TaskRunnerOptions } from "nitro/types"; | ||
@@ -37,3 +37,3 @@ //#region src/nitro.d.ts | ||
| declare function createDevServer(nitro: Nitro): NitroDevServer; | ||
| declare class NitroDevServer extends NitroDevApp implements DevRPCHooks { | ||
| declare class NitroDevServer extends NitroDevApp implements RunnerRPCHooks { | ||
| #private; | ||
@@ -46,4 +46,4 @@ constructor(nitro: Nitro); | ||
| sendMessage(message: unknown): void; | ||
| onMessage(listener: DevMessageListener): void; | ||
| offMessage(listener: DevMessageListener): void; | ||
| onMessage(listener: RunnerMessageListener): void; | ||
| offMessage(listener: RunnerMessageListener): void; | ||
| } | ||
@@ -50,0 +50,0 @@ //#endregion |
+6
-30
@@ -1,33 +0,9 @@ | ||
| import "./_libs/c12.mjs"; | ||
| import "./_libs/gen-mapping.mjs"; | ||
| import "./_libs/magic-string.mjs"; | ||
| import "./_libs/acorn.mjs"; | ||
| import "./_libs/confbox.mjs"; | ||
| import "./_libs/local-pkg.mjs"; | ||
| import "./_libs/js-tokens.mjs"; | ||
| import "./_libs/strip-literal.mjs"; | ||
| import "./_libs/unimport.mjs"; | ||
| import "./_libs/picomatch.mjs"; | ||
| import "./_libs/fdir.mjs"; | ||
| import "./_libs/tinyglobby.mjs"; | ||
| import "./_libs/compatx.mjs"; | ||
| import "./_libs/klona.mjs"; | ||
| import "./_libs/std-env.mjs"; | ||
| import { a as createNitro, c as loadOptions, i as build, n as prepare, o as listTasks, r as copyPublicAssets, s as runTask, t as prerender } from "./_chunks/B-D1JOIz.mjs"; | ||
| import "./_libs/escape-string-regexp.mjs"; | ||
| import "./_common.mjs"; | ||
| import { D as prepare, M as build, O as copyPublicAssets, _ as writeTypes, m as getBuildInfo } from "./_build/common.mjs"; | ||
| import "./_libs/rc9+c12+dotenv.mjs"; | ||
| import { a as loadOptions, i as createNitro, n as runTask, r as prerender, t as listTasks } from "./_chunks/nitro.mjs"; | ||
| import "./_libs/tsconfck.mjs"; | ||
| import "./_libs/dot-prop.mjs"; | ||
| import "./_chunks/C7CbzoI1.mjs"; | ||
| import { n as writeTypes } from "./_chunks/ANM1K1bE.mjs"; | ||
| import "./_libs/rou3.mjs"; | ||
| import "./_libs/mime.mjs"; | ||
| import "./_libs/pathe.mjs"; | ||
| import "./_libs/untyped.mjs"; | ||
| import "./_libs/knitwork.mjs"; | ||
| import { t as getBuildInfo } from "./_build/common.mjs"; | ||
| import "./_libs/httpxy.mjs"; | ||
| import { n as createDevServer } from "./_dev.mjs"; | ||
| import "./_libs/chokidar.mjs"; | ||
| import "./_libs/ultrahtml.mjs"; | ||
| import "./_chunks/nitro2.mjs"; | ||
| import { n as createDevServer } from "./_chunks/dev.mjs"; | ||
| export { build, copyPublicAssets, createDevServer, createNitro, getBuildInfo, listTasks, loadOptions, prepare, prerender, runTask, writeTypes }; |
@@ -1,2 +0,2 @@ | ||
| import { k as resolve } from "../../_libs/c12.mjs"; | ||
| import { ct as resolve } from "../../_build/common.mjs"; | ||
| import { t as defineCommand } from "../../_libs/citty.mjs"; | ||
@@ -3,0 +3,0 @@ import { t as commonArgs } from "./common.mjs"; |
@@ -1,10 +0,4 @@ | ||
| import { k as resolve } from "../../_libs/c12.mjs"; | ||
| import "../../_libs/std-env.mjs"; | ||
| import "../../_libs/dot-prop.mjs"; | ||
| import "../../_chunks/C7CbzoI1.mjs"; | ||
| import "../../_libs/mime.mjs"; | ||
| import "../../_build/common.mjs"; | ||
| import "../../_libs/httpxy.mjs"; | ||
| import { t as NitroDevServer } from "../../_dev.mjs"; | ||
| import "../../_libs/chokidar.mjs"; | ||
| import { ct as resolve } from "../../_build/common.mjs"; | ||
| import "../../_libs/rc9+c12+dotenv.mjs"; | ||
| import { t as NitroDevServer } from "../../_chunks/dev.mjs"; | ||
| import { t as defineCommand } from "../../_libs/citty.mjs"; | ||
@@ -57,4 +51,4 @@ import { t as commonArgs } from "./common.mjs"; | ||
| await new NitroDevServer(nitro).listen({ | ||
| port: args.port, | ||
| hostname: args.host | ||
| port: args.port || nitro.options.devServer.port, | ||
| hostname: args.host || nitro.options.devServer.hostname | ||
| }); | ||
@@ -61,0 +55,0 @@ await prepare(nitro); |
@@ -1,2 +0,2 @@ | ||
| import { k as resolve } from "../../_libs/c12.mjs"; | ||
| import { ct as resolve } from "../../_build/common.mjs"; | ||
| import { t as defineCommand } from "../../_libs/citty.mjs"; | ||
@@ -3,0 +3,0 @@ import { consola } from "consola"; |
@@ -1,2 +0,2 @@ | ||
| import { k as resolve } from "../../_libs/c12.mjs"; | ||
| import { ct as resolve } from "../../_build/common.mjs"; | ||
| import { t as defineCommand } from "../../_libs/citty.mjs"; | ||
@@ -3,0 +3,0 @@ import { t as commonArgs } from "./common.mjs"; |
@@ -1,2 +0,2 @@ | ||
| import { k as resolve } from "../../_libs/c12.mjs"; | ||
| import { ct as resolve } from "../../_build/common.mjs"; | ||
| import { t as defineCommand } from "../../_libs/citty.mjs"; | ||
@@ -3,0 +3,0 @@ import { consola } from "consola"; |
@@ -1,169 +0,139 @@ | ||
| // src/base.ts | ||
| import kleur from "kleur"; | ||
| var Colors = class { | ||
| black(text) { | ||
| return this.transform("black", text); | ||
| } | ||
| red(text) { | ||
| return this.transform("red", text); | ||
| } | ||
| green(text) { | ||
| return this.transform("green", text); | ||
| } | ||
| yellow(text) { | ||
| return this.transform("yellow", text); | ||
| } | ||
| blue(text) { | ||
| return this.transform("blue", text); | ||
| } | ||
| magenta(text) { | ||
| return this.transform("magenta", text); | ||
| } | ||
| cyan(text) { | ||
| return this.transform("cyan", text); | ||
| } | ||
| white(text) { | ||
| return this.transform("white", text); | ||
| } | ||
| gray(text) { | ||
| return this.transform("gray", text); | ||
| } | ||
| grey(text) { | ||
| return this.transform("grey", text); | ||
| } | ||
| bgBlack(text) { | ||
| return this.transform("bgBlack", text); | ||
| } | ||
| bgRed(text) { | ||
| return this.transform("bgRed", text); | ||
| } | ||
| bgGreen(text) { | ||
| return this.transform("bgGreen", text); | ||
| } | ||
| bgYellow(text) { | ||
| return this.transform("bgYellow", text); | ||
| } | ||
| bgBlue(text) { | ||
| return this.transform("bgBlue", text); | ||
| } | ||
| bgMagenta(text) { | ||
| return this.transform("bgMagenta", text); | ||
| } | ||
| bgCyan(text) { | ||
| return this.transform("bgCyan", text); | ||
| } | ||
| bgWhite(text) { | ||
| return this.transform("bgWhite", text); | ||
| } | ||
| reset(text) { | ||
| return this.transform("reset", text); | ||
| } | ||
| bold(text) { | ||
| return this.transform("bold", text); | ||
| } | ||
| dim(text) { | ||
| return this.transform("dim", text); | ||
| } | ||
| italic(text) { | ||
| return this.transform("italic", text); | ||
| } | ||
| underline(text) { | ||
| return this.transform("underline", text); | ||
| } | ||
| inverse(text) { | ||
| return this.transform("inverse", text); | ||
| } | ||
| hidden(text) { | ||
| return this.transform("hidden", text); | ||
| } | ||
| strikethrough(text) { | ||
| return this.transform("strikethrough", text); | ||
| } | ||
| black(text) { | ||
| return this.transform("black", text); | ||
| } | ||
| red(text) { | ||
| return this.transform("red", text); | ||
| } | ||
| green(text) { | ||
| return this.transform("green", text); | ||
| } | ||
| yellow(text) { | ||
| return this.transform("yellow", text); | ||
| } | ||
| blue(text) { | ||
| return this.transform("blue", text); | ||
| } | ||
| magenta(text) { | ||
| return this.transform("magenta", text); | ||
| } | ||
| cyan(text) { | ||
| return this.transform("cyan", text); | ||
| } | ||
| white(text) { | ||
| return this.transform("white", text); | ||
| } | ||
| gray(text) { | ||
| return this.transform("gray", text); | ||
| } | ||
| grey(text) { | ||
| return this.transform("grey", text); | ||
| } | ||
| bgBlack(text) { | ||
| return this.transform("bgBlack", text); | ||
| } | ||
| bgRed(text) { | ||
| return this.transform("bgRed", text); | ||
| } | ||
| bgGreen(text) { | ||
| return this.transform("bgGreen", text); | ||
| } | ||
| bgYellow(text) { | ||
| return this.transform("bgYellow", text); | ||
| } | ||
| bgBlue(text) { | ||
| return this.transform("bgBlue", text); | ||
| } | ||
| bgMagenta(text) { | ||
| return this.transform("bgMagenta", text); | ||
| } | ||
| bgCyan(text) { | ||
| return this.transform("bgCyan", text); | ||
| } | ||
| bgWhite(text) { | ||
| return this.transform("bgWhite", text); | ||
| } | ||
| reset(text) { | ||
| return this.transform("reset", text); | ||
| } | ||
| bold(text) { | ||
| return this.transform("bold", text); | ||
| } | ||
| dim(text) { | ||
| return this.transform("dim", text); | ||
| } | ||
| italic(text) { | ||
| return this.transform("italic", text); | ||
| } | ||
| underline(text) { | ||
| return this.transform("underline", text); | ||
| } | ||
| inverse(text) { | ||
| return this.transform("inverse", text); | ||
| } | ||
| hidden(text) { | ||
| return this.transform("hidden", text); | ||
| } | ||
| strikethrough(text) { | ||
| return this.transform("strikethrough", text); | ||
| } | ||
| }; | ||
| // src/raw.ts | ||
| var Raw = class extends Colors { | ||
| #transformations = []; | ||
| #dispose(value, callback) { | ||
| callback(); | ||
| return value; | ||
| } | ||
| transform(transformation, text) { | ||
| this.#transformations.push(transformation); | ||
| if (text !== void 0) { | ||
| const transformations = this.#transformations.concat([text]).join("("); | ||
| const closingWrapping = new Array(this.#transformations.length + 1).join(")"); | ||
| return this.#dispose(`${transformations}${closingWrapping}`, () => { | ||
| this.#transformations = []; | ||
| }); | ||
| } | ||
| return this; | ||
| } | ||
| #transformations = []; | ||
| #dispose(value, callback) { | ||
| callback(); | ||
| return value; | ||
| } | ||
| transform(transformation, text) { | ||
| this.#transformations.push(transformation); | ||
| if (text !== void 0) { | ||
| const transformations = this.#transformations.concat([text]).join("("); | ||
| const closingWrapping = new Array(this.#transformations.length + 1).join(")"); | ||
| return this.#dispose(`${transformations}${closingWrapping}`, () => { | ||
| this.#transformations = []; | ||
| }); | ||
| } | ||
| return this; | ||
| } | ||
| }; | ||
| // src/kleur.ts | ||
| import kleur from "kleur"; | ||
| var Kleur = class extends Colors { | ||
| #chain; | ||
| constructor() { | ||
| super(); | ||
| kleur.enabled = true; | ||
| } | ||
| #dispose(value, callback) { | ||
| callback(); | ||
| return value; | ||
| } | ||
| transform(transformation, text) { | ||
| if (text !== void 0) { | ||
| if (this.#chain) { | ||
| return this.#dispose(this.#chain[transformation](text), () => { | ||
| this.#chain = void 0; | ||
| }); | ||
| } | ||
| return kleur[transformation](text); | ||
| } | ||
| if (this.#chain) { | ||
| this.#chain = this.#chain[transformation](); | ||
| } else { | ||
| this.#chain = kleur[transformation](); | ||
| } | ||
| return this; | ||
| } | ||
| #chain; | ||
| constructor() { | ||
| super(); | ||
| kleur.enabled = true; | ||
| } | ||
| #dispose(value, callback) { | ||
| callback(); | ||
| return value; | ||
| } | ||
| transform(transformation, text) { | ||
| if (text !== void 0) { | ||
| if (this.#chain) return this.#dispose(this.#chain[transformation](text), () => { | ||
| this.#chain = void 0; | ||
| }); | ||
| return kleur[transformation](text); | ||
| } | ||
| if (this.#chain) this.#chain = this.#chain[transformation](); | ||
| else this.#chain = kleur[transformation](); | ||
| return this; | ||
| } | ||
| }; | ||
| // src/silent.ts | ||
| var Silent = class extends Colors { | ||
| transform(_, text) { | ||
| if (text !== void 0) { | ||
| return String(text); | ||
| } | ||
| return this; | ||
| } | ||
| transform(_, text) { | ||
| if (text !== void 0) return String(text); | ||
| return this; | ||
| } | ||
| }; | ||
| // index.ts | ||
| var useColors = { | ||
| /** | ||
| * Kleur implementation | ||
| */ | ||
| ansi() { | ||
| return new Kleur(); | ||
| }, | ||
| /** | ||
| * Silent implementation. Returns the string | ||
| * as it is | ||
| */ | ||
| silent() { | ||
| return new Silent(); | ||
| }, | ||
| /** | ||
| * Raw implementation. Wraps string with applied | ||
| * transformations as plain text. | ||
| */ | ||
| raw() { | ||
| return new Raw(); | ||
| } | ||
| var colors_default = { | ||
| ansi() { | ||
| return new Kleur(); | ||
| }, | ||
| silent() { | ||
| return new Silent(); | ||
| }, | ||
| raw() { | ||
| return new Raw(); | ||
| } | ||
| }; | ||
| var index_default = useColors; | ||
| export { | ||
| index_default as default | ||
| }; | ||
| export { colors_default as default }; |
| { | ||
| "name": "@poppinss/colors", | ||
| "version": "4.1.5", | ||
| "version": "4.1.6", | ||
| "description": "A wrapper on top of kleur with ability to write test against the color functions", | ||
@@ -23,3 +23,3 @@ "main": "build/index.js", | ||
| "precompile": "npm run lint && npm run clean", | ||
| "compile": "tsup-node && tsc --emitDeclarationOnly --declaration", | ||
| "compile": "tsdown && tsc --emitDeclarationOnly --declaration", | ||
| "clean": "del-cli build", | ||
@@ -33,18 +33,17 @@ "build": "npm run compile", | ||
| "devDependencies": { | ||
| "@adonisjs/eslint-config": "^3.0.0-next.0", | ||
| "@adonisjs/eslint-config": "^3.0.0-next.5", | ||
| "@adonisjs/prettier-config": "^1.4.5", | ||
| "@adonisjs/tsconfig": "^2.0.0-next.0", | ||
| "@japa/assert": "^4.0.1", | ||
| "@japa/runner": "^4.2.0", | ||
| "@poppinss/ts-exec": "^1.4.0", | ||
| "@release-it/conventional-changelog": "^10.0.1", | ||
| "@swc/core": "^1.12.9", | ||
| "@types/node": "^24.0.10", | ||
| "@adonisjs/tsconfig": "^2.0.0-next.3", | ||
| "@japa/assert": "^4.1.1", | ||
| "@japa/runner": "^4.4.0", | ||
| "@poppinss/ts-exec": "^1.4.1", | ||
| "@release-it/conventional-changelog": "^10.0.3", | ||
| "@types/node": "^25.0.1", | ||
| "c8": "^10.1.3", | ||
| "del-cli": "^6.0.0", | ||
| "eslint": "^9.30.1", | ||
| "prettier": "^3.6.2", | ||
| "release-it": "^19.0.3", | ||
| "tsup": "^8.5.0", | ||
| "typescript": "^5.8.3" | ||
| "del-cli": "^7.0.0", | ||
| "eslint": "^9.39.1", | ||
| "prettier": "^3.7.4", | ||
| "release-it": "^19.1.0", | ||
| "tsdown": "^0.17.3", | ||
| "typescript": "^5.9.3" | ||
| }, | ||
@@ -72,3 +71,3 @@ "dependencies": { | ||
| }, | ||
| "tsup": { | ||
| "tsdown": { | ||
| "entry": [ | ||
@@ -81,4 +80,7 @@ "./index.ts", | ||
| "format": "esm", | ||
| "minify": "dce-only", | ||
| "fixedExtension": false, | ||
| "dts": false, | ||
| "sourcemap": false, | ||
| "treeshake": false, | ||
| "sourcemaps": false, | ||
| "target": "esnext" | ||
@@ -85,0 +87,0 @@ }, |
@@ -1,63 +0,44 @@ | ||
| // src/exception.ts | ||
| import { format } from "util"; | ||
| import { format } from "node:util"; | ||
| var Exception = class extends Error { | ||
| /** | ||
| * Name of the class that raised the exception. | ||
| */ | ||
| name; | ||
| /** | ||
| * A status code for the error. Usually helpful when converting errors | ||
| * to HTTP responses. | ||
| */ | ||
| status; | ||
| constructor(message, options) { | ||
| super(message, options); | ||
| const ErrorConstructor = this.constructor; | ||
| this.name = ErrorConstructor.name; | ||
| this.message = message || ErrorConstructor.message || ""; | ||
| this.status = options?.status || ErrorConstructor.status || 500; | ||
| const code = options?.code || ErrorConstructor.code; | ||
| if (code !== void 0) { | ||
| this.code = code; | ||
| } | ||
| const help = ErrorConstructor.help; | ||
| if (help !== void 0) { | ||
| this.help = help; | ||
| } | ||
| Error.captureStackTrace(this, ErrorConstructor); | ||
| } | ||
| get [Symbol.toStringTag]() { | ||
| return this.constructor.name; | ||
| } | ||
| toString() { | ||
| if (this.code) { | ||
| return `${this.name} [${this.code}]: ${this.message}`; | ||
| } | ||
| return `${this.name}: ${this.message}`; | ||
| } | ||
| name; | ||
| status; | ||
| constructor(message, options) { | ||
| super(message, options); | ||
| const ErrorConstructor = this.constructor; | ||
| this.name = ErrorConstructor.name; | ||
| this.message = message || ErrorConstructor.message || ""; | ||
| this.status = options?.status || ErrorConstructor.status || 500; | ||
| const code = options?.code || ErrorConstructor.code; | ||
| if (code !== void 0) this.code = code; | ||
| const help = ErrorConstructor.help; | ||
| if (help !== void 0) this.help = help; | ||
| Error.captureStackTrace(this, ErrorConstructor); | ||
| } | ||
| get [Symbol.toStringTag]() { | ||
| return this.constructor.name; | ||
| } | ||
| toString() { | ||
| if (this.code) return `${this.name} [${this.code}]: ${this.message}`; | ||
| return `${this.name}: ${this.message}`; | ||
| } | ||
| }; | ||
| var InvalidArgumentsException = class extends Exception { | ||
| static code = "E_INVALID_ARGUMENTS_EXCEPTION"; | ||
| static status = 500; | ||
| static code = "E_INVALID_ARGUMENTS_EXCEPTION"; | ||
| static status = 500; | ||
| }; | ||
| var RuntimeException = class extends Exception { | ||
| static code = "E_RUNTIME_EXCEPTION"; | ||
| static status = 500; | ||
| static code = "E_RUNTIME_EXCEPTION"; | ||
| static status = 500; | ||
| }; | ||
| function createError(message, code, status) { | ||
| return class extends Exception { | ||
| static message = message; | ||
| static code = code; | ||
| static status = status; | ||
| constructor(args, options) { | ||
| super(format(message, ...args || []), options); | ||
| this.name = "Exception"; | ||
| } | ||
| }; | ||
| return class extends Exception { | ||
| static message = message; | ||
| static code = code; | ||
| static status = status; | ||
| constructor(args, options) { | ||
| super(format(message, ...args || []), options); | ||
| this.name = "Exception"; | ||
| } | ||
| }; | ||
| } | ||
| export { | ||
| Exception, | ||
| InvalidArgumentsException, | ||
| RuntimeException, | ||
| createError | ||
| }; | ||
| export { Exception, InvalidArgumentsException, RuntimeException, createError }; |
| { | ||
| "name": "@poppinss/exception", | ||
| "description": "Utility to create custom exceptions", | ||
| "version": "1.2.2", | ||
| "version": "1.2.3", | ||
| "type": "module", | ||
@@ -22,3 +22,3 @@ "files": [ | ||
| "precompile": "npm run lint", | ||
| "compile": "tsup-node && tsc --emitDeclarationOnly --declaration", | ||
| "compile": "tsdown && tsc --emitDeclarationOnly --declaration", | ||
| "build": "npm run compile", | ||
@@ -31,17 +31,17 @@ "version": "npm run build", | ||
| "devDependencies": { | ||
| "@adonisjs/eslint-config": "^3.0.0-next.0", | ||
| "@adonisjs/eslint-config": "^3.0.0-next.5", | ||
| "@adonisjs/prettier-config": "^1.4.5", | ||
| "@adonisjs/tsconfig": "^2.0.0-next.0", | ||
| "@japa/expect": "^3.0.4", | ||
| "@adonisjs/tsconfig": "^2.0.0-next.3", | ||
| "@japa/expect": "^3.0.6", | ||
| "@japa/expect-type": "^2.0.3", | ||
| "@japa/runner": "^4.2.0", | ||
| "@poppinss/ts-exec": "^1.4.0", | ||
| "@release-it/conventional-changelog": "^10.0.1", | ||
| "@types/node": "^24.0.10", | ||
| "@japa/runner": "^4.4.0", | ||
| "@poppinss/ts-exec": "^1.4.1", | ||
| "@release-it/conventional-changelog": "^10.0.3", | ||
| "@types/node": "^25.0.1", | ||
| "c8": "^10.1.3", | ||
| "eslint": "^9.30.1", | ||
| "prettier": "^3.6.2", | ||
| "release-it": "^19.0.3", | ||
| "tsup": "^8.5.0", | ||
| "typescript": "^5.8.3" | ||
| "eslint": "^9.39.1", | ||
| "prettier": "^3.7.4", | ||
| "release-it": "^19.1.0", | ||
| "tsdown": "^0.17.3", | ||
| "typescript": "^5.9.3" | ||
| }, | ||
@@ -63,3 +63,3 @@ "homepage": "https://github.com/poppinss/exception#readme", | ||
| }, | ||
| "tsup": { | ||
| "tsdown": { | ||
| "entry": [ | ||
@@ -71,4 +71,7 @@ "index.ts" | ||
| "format": "esm", | ||
| "minify": "dce-only", | ||
| "fixedExtension": false, | ||
| "dts": false, | ||
| "sourcemap": false, | ||
| "treeshake": false, | ||
| "sourcemaps": false, | ||
| "target": "esnext" | ||
@@ -75,0 +78,0 @@ }, |
@@ -269,8 +269,42 @@ import { keysOf } from './utilities.js'; | ||
| } | ||
| function validatePredicateArray(predicateArray, allowEmpty) { | ||
| if (predicateArray.length === 0) { | ||
| if (allowEmpty) { | ||
| // Next major release: throw for empty predicate arrays to avoid vacuous results. | ||
| // throw new TypeError('Invalid predicate array'); | ||
| } | ||
| else { | ||
| throw new TypeError('Invalid predicate array'); | ||
| } | ||
| return; | ||
| } | ||
| for (const predicate of predicateArray) { | ||
| if (!isFunction(predicate)) { | ||
| throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); | ||
| } | ||
| } | ||
| } | ||
| export function isAll(predicate, ...values) { | ||
| if (Array.isArray(predicate)) { | ||
| const predicateArray = predicate; | ||
| validatePredicateArray(predicateArray, values.length === 0); | ||
| const combinedPredicate = (value) => predicateArray.every(singlePredicate => singlePredicate(value)); | ||
| if (values.length === 0) { | ||
| return combinedPredicate; | ||
| } | ||
| return predicateOnArray(Array.prototype.every, combinedPredicate, values); | ||
| } | ||
| return predicateOnArray(Array.prototype.every, predicate, values); | ||
| } | ||
| export function isAny(predicate, ...values) { | ||
| const predicates = isArray(predicate) ? predicate : [predicate]; | ||
| return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values)); | ||
| if (Array.isArray(predicate)) { | ||
| const predicateArray = predicate; | ||
| validatePredicateArray(predicateArray, values.length === 0); | ||
| const combinedPredicate = (value) => predicateArray.some(singlePredicate => singlePredicate(value)); | ||
| if (values.length === 0) { | ||
| return combinedPredicate; | ||
| } | ||
| return predicateOnArray(Array.prototype.some, combinedPredicate, values); | ||
| } | ||
| return predicateOnArray(Array.prototype.some, predicate, values); | ||
| } | ||
@@ -838,4 +872,8 @@ export function isOptional(value, predicate) { | ||
| export function assertAll(predicate, ...values) { | ||
| if (values.length === 0) { | ||
| throw new TypeError('Invalid number of values'); | ||
| } | ||
| if (!isAll(predicate, ...values)) { | ||
| const expectedType = isIsMethodName(predicate.name) ? methodTypeMap[predicate.name] : 'predicate returns truthy for all values'; | ||
| const predicateFunction = predicate; | ||
| const expectedType = !Array.isArray(predicate) && isIsMethodName(predicateFunction.name) ? methodTypeMap[predicateFunction.name] : 'predicate returns truthy for all values'; | ||
| throw new TypeError(typeErrorMessageMultipleValues(expectedType, values)); | ||
@@ -845,5 +883,8 @@ } | ||
| export function assertAny(predicate, ...values) { | ||
| if (values.length === 0) { | ||
| throw new TypeError('Invalid number of values'); | ||
| } | ||
| if (!isAny(predicate, ...values)) { | ||
| const predicates = isArray(predicate) ? predicate : [predicate]; | ||
| const expectedTypes = predicates.map(predicate => isIsMethodName(predicate.name) ? methodTypeMap[predicate.name] : 'predicate returns truthy for any value'); | ||
| const predicates = Array.isArray(predicate) ? predicate : [predicate]; | ||
| const expectedTypes = predicates.map(singlePredicate => isIsMethodName(singlePredicate.name) ? methodTypeMap[singlePredicate.name] : 'predicate returns truthy for any value'); | ||
| throw new TypeError(typeErrorMessageMultipleValues(expectedTypes, values)); | ||
@@ -850,0 +891,0 @@ } |
| { | ||
| "name": "@sindresorhus/is", | ||
| "version": "7.1.1", | ||
| "version": "7.2.0", | ||
| "description": "Type check values", | ||
@@ -5,0 +5,0 @@ "license": "MIT", |
| var Xt=Object.defineProperty;var w=t=>e=>{var s=t[e];if(s)return s();throw new Error("Module not found in bundle: "+e)};var a=(t,e)=>()=>(t&&(e=t(t=0)),e);var p=(t,e)=>{for(var s in e)Xt(t,s,{get:e[s],enumerable:!0})};var P={};p(P,{default:()=>Wt});var Wt,F=a(()=>{Wt=[{type:"cmnt",match:/(;|#).*/gm},{expand:"str"},{expand:"num"},{type:"num",match:/\$[\da-fA-F]*\b/g},{type:"kwd",match:/^[a-z]+\s+[a-z.]+\b/gm,sub:[{type:"func",match:/^[a-z]+/g}]},{type:"kwd",match:/^\t*[a-z][a-z\d]*\b/gm},{match:/%|\$/g,type:"oper"}]});var $={};p($,{default:()=>T});var M,T,f=a(()=>{M={type:"var",match:/\$\w+|\${[^}]*}|\$\([^)]*\)/g},T=[{sub:"todo",match:/#.*/g},{type:"str",match:/(["'])((?!\1)[^\r\n\\]|\\[^])*\1?/g,sub:[M]},{type:"oper",match:/(?<=\s|^)\.*\/[a-z/_.-]+/gi},{type:"kwd",match:/\s-[a-zA-Z]+|$<|[&|;]+|\b(unset|readonly|shift|export|if|fi|else|elif|while|do|done|for|until|case|esac|break|continue|exit|return|trap|wait|eval|exec|then|declare|enable|local|select|typeset|time|add|remove|install|update|delete)(?=\s|$)/g},{expand:"num"},{type:"func",match:/(?<=(^|\||\&\&|\;)\s*)[a-z_.-]+(?=\s|$)/gmi},{type:"bool",match:/(?<=\s|^)(true|false)(?=\s|$)/g},{type:"oper",match:/[=(){}<>!]+/g},{type:"var",match:/(?<=\s|^)[\w_]+(?=\s*=)/g},M]});var v={};p(v,{default:()=>jt});var jt,B=a(()=>{jt=[{match:/[^\[\->+.<\]\s].*/g,sub:"todo"},{type:"func",match:/\.+/g},{type:"kwd",match:/[<>]+/g},{type:"oper",match:/[+-]+/g}]});var G={};p(G,{default:()=>Kt});var Kt,H=a(()=>{Kt=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/#\s*include (<.*>|".*")/g,sub:[{type:"str",match:/(<|").*/g}]},{match:/asm\s*{[^}]*}/g,sub:[{type:"kwd",match:/^asm/g},{match:/[^{}]*(?=}$)/g,sub:"asm"}]},{type:"kwd",match:/\*|&|#[a-z]+\b|\b(asm|auto|double|int|struct|break|else|long|switch|case|enum|register|typedef|char|extern|return|union|const|float|short|unsigned|continue|for|signed|void|default|goto|sizeof|volatile|do|if|static|while)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var k={};p(k,{default:()=>Vt});var Vt,z=a(()=>{Vt=[{match:/\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/@\w+\b|\b(and|not|only|or)\b|\b[a-z-]+(?=[^{}]*{)/g},{type:"var",match:/\b[\w-]+(?=\s*:)|(::?|\.)[\w-]+(?=[^{}]*{)/g},{type:"func",match:/#[\w-]+(?=[^{}]*{)/g},{type:"num",match:/#[\da-f]{3,8}/g},{type:"num",match:/\d+(\.\d+)?(cm|mm|in|px|pt|pc|em|ex|ch|rem|vm|vh|vmin|vmax|%)?/g,sub:[{type:"var",match:/[a-z]+|%/g}]},{match:/url\([^)]*\)/g,sub:[{type:"func",match:/url(?=\()/g},{type:"str",match:/[^()]+/g}]},{type:"func",match:/\b[a-zA-Z]\w*(?=\s*\()/g},{type:"num",match:/\b[a-z-]+\b/g}]});var _={};p(_,{default:()=>qt});var qt,Y=a(()=>{qt=[{expand:"strDouble"},{type:"oper",match:/,/g}]});var Z={};p(Z,{default:()=>I});var I,N=a(()=>{I=[{type:"deleted",match:/^[-<].*/gm},{type:"insert",match:/^[+>].*/gm},{type:"kwd",match:/!.*/gm},{type:"section",match:/^@@.*@@$|^\d.*|^([*-+])\1\1.*/gm}]});var X={};p(X,{default:()=>Qt});var Qt,W=a(()=>{f();Qt=[{type:"kwd",match:/^(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)\b/gmi},...T]});var j={};p(j,{default:()=>Jt});var Jt,K=a(()=>{N();Jt=[{match:/^#.*/gm,sub:"todo"},{expand:"str"},...I,{type:"func",match:/^(\$ )?git(\s.*)?$/gm},{type:"kwd",match:/^commit \w+$/gm}]});var V={};p(V,{default:()=>te});var te,q=a(()=>{te=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\*|&|\b(break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go|goto|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"oper",match:/[+\-*\/%&|^~=!<>.^-]+/g}]});var J={};p(J,{default:()=>A,name:()=>E,properties:()=>l,xmlElement:()=>o});var Q,ee,E,l,o,A,R=a(()=>{Q=":A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD",ee=Q+"\\-\\.0-9\xB7\u0300-\u036F\u203F-\u2040",E=`[${Q}][${ee}]*`,l=`\\s*(\\s+${E}\\s*(=\\s*([^"']\\S*|("|')(\\\\[^]|(?!\\4)[^])*\\4?)?)?\\s*)*`,o={match:RegExp(`<[/!?]?${E}${l}[/!?]?>`,"g"),sub:[{type:"var",match:RegExp(`^<[/!?]?${E}`,"g"),sub:[{type:"oper",match:/^<[\/!?]?/g}]},{type:"str",match:/=\s*([^"']\S*|("|')(\\[^]|(?!\2)[^])*\2?)/g,sub:[{type:"oper",match:/^=/g}]},{type:"oper",match:/[\/!?]?>/g},{type:"class",match:RegExp(E,"g")}]},A=[{match:/<!--((?!-->)[^])*-->/g,sub:"todo"},{type:"class",match:/<!\[CDATA\[[\s\S]*?\]\]>/gi},o,{type:"str",match:RegExp(`<\\?${E}([^?]|\\?[^?>])*\\?+>`,"g"),sub:[{type:"var",match:RegExp(`^<\\?${E}`,"g"),sub:[{type:"oper",match:/^<\?/g}]},{type:"oper",match:/\?+>$/g}]},{type:"var",match:/&(#x?)?[\da-z]{1,8};/gi}]});var tt={};p(tt,{default:()=>ae});var ae,et=a(()=>{R();ae=[{type:"class",match:/<!DOCTYPE("[^"]*"|'[^']*'|[^"'>])*>/gi,sub:[{type:"str",match:/"[^"]*"|'[^']*'/g},{type:"oper",match:/^<!|>$/g},{type:"var",match:/DOCTYPE/gi}]},{match:RegExp(`<style${l}>((?!</style>)[^])*</style\\s*>`,"g"),sub:[{match:RegExp(`^<style${l}>`,"g"),sub:o.sub},{match:RegExp(`${o.match}|[^]*(?=</style\\s*>$)`,"g"),sub:"css"},o]},{match:RegExp(`<script${l}>((?!<\/script>)[^])*<\/script\\s*>`,"g"),sub:[{match:RegExp(`^<script${l}>`,"g"),sub:o.sub},{match:RegExp(`${o.match}|[^]*(?=<\/script\\s*>$)`,"g"),sub:"js"},o]},...A]});var pe,u,d=a(()=>{pe=[["bash",[/#!(\/usr)?\/bin\/bash/g,500],[/\b(if|elif|then|fi|echo)\b|\$/g,10]],["html",[/<\/?[a-z-]+[^\n>]*>/g,10],[/^\s+<!DOCTYPE\s+html/g,500]],["http",[/^(GET|HEAD|POST|PUT|DELETE|PATCH|HTTP)\b/g,500]],["js",[/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require)\b/g,10]],["ts",[/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require|implements|interface|namespace)\b/g,10]],["py",[/\b(def|print|class|and|or|lambda)\b/g,10]],["sql",[/\b(SELECT|INSERT|FROM)\b/g,50]],["pl",[/#!(\/usr)?\/bin\/perl/g,500],[/\b(use|print)\b|\$/g,10]],["lua",[/#!(\/usr)?\/bin\/lua/g,500]],["make",[/\b(ifneq|endif|if|elif|then|fi|echo|.PHONY|^[a-z]+ ?:$)\b|\$/gm,10]],["uri",[/https?:|mailto:|tel:|ftp:/g,30]],["css",[/^(@import|@page|@media|(\.|#)[a-z]+)/gm,20]],["diff",[/^[+><-]/gm,10],[/^@@ ?[-+,0-9 ]+ ?@@/gm,25]],["md",[/^(>|\t\*|\t\d+.)/gm,10],[/\[.*\](.*)/g,10]],["docker",[/^(FROM|ENTRYPOINT|RUN)/gm,500]],["xml",[/<\/?[a-z-]+[^\n>]*>/g,10],[/^<\?xml/g,500]],["c",[/#include\b|\bprintf\s+\(/g,100]],["rs",[/^\s+(use|fn|mut|match)\b/gm,100]],["go",[/\b(func|fmt|package)\b/g,100]],["java",[/^import\s+java/gm,500]],["asm",[/^(section|global main|extern|\t(call|mov|ret))/gm,100]],["css",[/^(@import|@page|@media|(\.|#)[a-z]+)/gm,20]],["json",[/\b(true|false|null|\{})\b|\"[^"]+\":/g,10]],["yaml",[/^(\s+)?[a-z][a-z0-9]*:/gmi,10]]],u=t=>pe.map(([e,...s])=>[e,s.reduce((c,[m,n])=>c+[...t.matchAll(m)].length*n,0)]).filter(([e,s])=>s>20).sort((e,s)=>s[1]-e[1])[0]?.[0]||"plain"});var at={};p(at,{default:()=>se});var se,pt=a(()=>{d();se=[{type:"kwd",match:/^(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI|SEARCH)\b/gm},{expand:"str"},{type:"section",match:/\bHTTP\/[\d.]+\b/g},{expand:"num"},{type:"oper",match:/[,;:=]/g},{type:"var",match:/[a-zA-Z][\w-]*(?=:)/g},{match:/\n\n[^]*/g,sub:u}]});var st={};p(st,{default:()=>ce});var ce,ct=a(()=>{ce=[{match:/(^[ \f\t\v]*)[#;].*/gm,sub:"todo"},{type:"str",match:/.*/g},{type:"var",match:/.*(?==)/g},{type:"section",match:/^\s*\[.+\]\s*$/gm},{type:"oper",match:/=/g}]});var nt={};p(nt,{default:()=>ne});var ne,mt=a(()=>{ne=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(abstract|assert|boolean|break|byte|case|catch|char|class|continue|const|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|package|private|protected|public|requires|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|transient|try|var|void|volatile|while)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var rt={};p(rt,{default:()=>O});var O,L=a(()=>{O=[{match:/\/\*\*((?!\*\/)[^])*(\*\/)?/g,sub:"jsdoc"},{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{match:/`((?!`)[^]|\\[^])*`?/g,sub:"js_template_literals"},{type:"kwd",match:/=>|\b(this|set|get|as|async|await|break|case|catch|class|const|constructor|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|if|implements|import|in|instanceof|interface|let|var|of|new|package|private|protected|public|return|static|super|switch|throw|throws|try|typeof|void|while|with|yield)\b/g},{match:/\/((?!\/)[^\r\n\\]|\\.)+\/[dgimsuy]*/g,sub:"regex"},{expand:"num"},{type:"num",match:/\b(NaN|null|undefined|[A-Z][A-Z_]*)\b/g},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z$_][\w$_]*(?=\s*((\?\.)?\s*\(|=\s*(\(?[\w,{}\[\])]+\)? =>|function\b)))/g}]});var ot={};p(ot,{default:()=>me,type:()=>re});var me,re,Et=a(()=>{me=[{match:new class{exec(t){let e=this.lastIndex,s,c=m=>{for(;++e<t.length-2;)if(t[e]=="{")c();else if(t[e]=="}")return};for(;e<t.length;++e)if(t[e-1]!="\\"&&t[e]=="$"&&t[e+1]=="{")return s=e++,c(e),this.lastIndex=e+1,{index:s,0:t.slice(s,e+1)};return null}},sub:[{type:"kwd",match:/^\${|}$/g},{match:/(?!^\$|{)[^]+(?=}$)/g,sub:"js"}]}],re="str"});var lt={};p(lt,{default:()=>x,type:()=>oe});var x,oe,S=a(()=>{x=[{type:"err",match:/\b(TODO|FIXME|DEBUG|OPTIMIZE|WARNING|XXX|BUG)\b/g},{type:"class",match:/\bIDEA\b/g},{type:"insert",match:/\b(CHANGED|FIX|CHANGE)\b/g},{type:"oper",match:/\bQUESTION\b/g}],oe="cmnt"});var ut={};p(ut,{default:()=>Ee,type:()=>le});var Ee,le,ht=a(()=>{S();Ee=[{type:"kwd",match:/@\w+/g},{type:"class",match:/{[\w\s|<>,.@\[\]]+}/g},{type:"var",match:/\[[\w\s="']+\]/g},...x],le="cmnt"});var it={};p(it,{default:()=>ue});var ue,gt=a(()=>{ue=[{type:"var",match:/(("|')((?!\2)[^\r\n\\]|\\[^])*\2|[a-zA-Z]\w*)(?=\s*:)/g},{expand:"str"},{expand:"num"},{type:"num",match:/\bnull\b/g},{type:"bool",match:/\b(true|false)\b/g}]});var dt={};p(dt,{default:()=>C});var C,D=a(()=>{d();C=[{type:"cmnt",match:/^>.*|(=|-)\1+/gm},{type:"class",match:/\*\*((?!\*\*).)*\*\*/g},{match:/```((?!```)[^])*\n```/g,sub:t=>({type:"kwd",sub:[{match:/\n[^]*(?=```)/g,sub:t.split(` | ||
| `)[0].slice(3)||u(t)}]})},{type:"str",match:/`[^`]*`/g},{type:"var",match:/~~((?!~~).)*~~/g},{type:"kwd",match:/\b_\S([^\n]*?\S)?_\b|\*\S([^\n]*?\S)?\*/g},{type:"kwd",match:/^\s*(\*|\d+\.)\s/gm},{type:"func",match:/\[[^\]]*]\([^)]*\)|<[^>]*>/g,sub:[{type:"oper",match:/^\[[^\]]*]/g}]}]});var bt={};p(bt,{default:()=>he});var he,yt=a(()=>{D();d();he=[{type:"insert",match:/(leanpub-start-insert)((?!leanpub-end-insert)[^])*(leanpub-end-insert)?/g,sub:[{type:"insert",match:/leanpub-(start|end)-insert/g},{match:/(?!leanpub-start-insert)((?!leanpub-end-insert)[^])*/g,sub:u}]},{type:"deleted",match:/(leanpub-start-delete)((?!leanpub-end-delete)[^])*(leanpub-end-delete)?/g,sub:[{type:"deleted",match:/leanpub-(start|end)-delete/g},{match:/(?!leanpub-start-delete)((?!leanpub-end-delete)[^])*/g,sub:u}]},...C]});var Tt={};p(Tt,{default:()=>ie});var ie,ft=a(()=>{ie=[{type:"cmnt",match:/^#.*/gm},{expand:"strDouble"},{expand:"num"},{type:"err",match:/\b(err(or)?|[a-z_-]*exception|warn|warning|failed|ko|invalid|not ?found|alert|fatal)\b/gi},{type:"num",match:/\b(null|undefined)\b/gi},{type:"bool",match:/\b(false|true|yes|no)\b/gi},{type:"oper",match:/\.|,/g}]});var It={};p(It,{default:()=>ge});var ge,Nt=a(()=>{ge=[{match:/^#!.*|--(\[(=*)\[((?!--\]\2\])[^])*--\]\2\]|.*)/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/\b(and|break|do|else|elseif|end|for|function|if|in|local|not|or|repeat|return|then|until|while)\b/g},{type:"bool",match:/\b(true|false|nil)\b/g},{type:"oper",match:/[+*/%^#=~<>:,.-]+/g},{expand:"num"},{type:"func",match:/[a-z_]+(?=\s*[({])/g}]});var At={};p(At,{default:()=>de});var de,Rt=a(()=>{de=[{match:/^\s*#.*/gm,sub:"todo"},{expand:"str"},{type:"oper",match:/[${}()]+/g},{type:"class",match:/.PHONY:/gm},{type:"section",match:/^[\w.]+:/gm},{type:"kwd",match:/\b(ifneq|endif)\b/g},{expand:"num"},{type:"var",match:/[A-Z_]+(?=\s*=)/g},{match:/^.*$/gm,sub:"bash"}]});var Ot={};p(Ot,{default:()=>be});var be,Lt=a(()=>{be=[{match:/#.*/g,sub:"todo"},{type:"str",match:/(["'])(\\[^]|(?!\1)[^])*\1?/g},{expand:"num"},{type:"kwd",match:/\b(any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|return|say|state|sub|switch|undef|unless|until|use|when|while|not|and|or|xor)\b/g},{type:"oper",match:/[-+*/%~!&<>|=?,]+/g},{type:"func",match:/[a-z_]+(?=\s*\()/g}]});var xt={};p(xt,{default:()=>ye});var ye,St=a(()=>{ye=[{expand:"strDouble"}]});var Ct={};p(Ct,{default:()=>Te});var Te,Dt=a(()=>{Te=[{match:/#.*/g,sub:"todo"},{match:/("""|''')(\\[^]|(?!\1)[^])*\1?/g,sub:"todo"},{type:"str",match:/f("|')(\\[^]|(?!\1).)*\1?|f((["'])\4\4)(\\[^]|(?!\3)[^])*\3?/gi,sub:[{type:"var",match:/{[^{}]*}/g,sub:[{match:/(?!^{)[^]*(?=}$)/g,sub:"py"}]}]},{expand:"str"},{type:"kwd",match:/\b(and|as|assert|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/g},{type:"bool",match:/\b(False|True|None)\b/g},{expand:"num"},{type:"func",match:/[a-z_]\w*(?=\s*\()/gi},{type:"oper",match:/[-/*+<>,=!&|^%]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var wt={};p(wt,{default:()=>fe,type:()=>Ie});var fe,Ie,Ut=a(()=>{fe=[{match:/^(?!\/).*/gm,sub:"todo"},{type:"num",match:/\[((?!\])[^\\]|\\.)*\]/g},{type:"kwd",match:/\||\^|\$|\\.|\w+($|\r|\n)/g},{type:"var",match:/\*|\+|\{\d+,\d+\}/g}],Ie="oper"});var Pt={};p(Pt,{default:()=>Ne});var Ne,Ft=a(()=>{Ne=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(as|break|const|continue|crate|else|enum|extern|false|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|true|type|unsafe|use|where|while|async|await|dyn|abstract|become|box|do|final|macro|override|priv|typeof|unsized|virtual|yield|try)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*!?\s*\()/g}]});var Mt={};p(Mt,{default:()=>Ae});var Ae,$t=a(()=>{Ae=[{match:/--.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"func",match:/\b(AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/g},{type:"kwd",match:/\b(ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|kwdS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:S|ING)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/g},{type:"num",match:/\.?\d[\d.oxa-fA-F-]*|\bNULL\b/g},{type:"bool",match:/\b(TRUE|FALSE)\b/g},{type:"oper",match:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|IN|ILIKE|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/g},{type:"var",match:/@\S+/g}]});var vt={};p(vt,{default:()=>Re});var Re,Bt=a(()=>{Re=[{match:/#.*/g,sub:"todo"},{type:"str",match:/("""|''')((?!\1)[^]|\\[^])*\1?/g},{expand:"str"},{type:"section",match:/^\[.+\]\s*$/gm},{type:"num",match:/\b(inf|nan)\b|\d[\d:ZT.-]*/g},{expand:"num"},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[+,.=-]/g},{type:"var",match:/\w+(?= \=)/g}]});var Gt={};p(Gt,{default:()=>Oe});var Oe,Ht=a(()=>{L();Oe=[{type:"type",match:/:\s*(any|void|number|boolean|string|object|never|enum)\b/g},{type:"kwd",match:/\b(type|namespace|typedef|interface|public|private|protected|implements|declare|abstract|readonly)\b/g},...O]});var kt={};p(kt,{default:()=>Le});var Le,zt=a(()=>{Le=[{match:/^#.*/gm,sub:"todo"},{type:"class",match:/^\w+(?=:?)/gm},{type:"num",match:/:\d+/g},{type:"oper",match:/[:/&?]|\w+=/g},{type:"func",match:/[.\w]+@|#[\w]+$/gm},{type:"var",match:/\w+\.\w+(\.\w+)*/g}]});var _t={};p(_t,{default:()=>xe});var xe,Yt=a(()=>{xe=[{match:/#.*/g,sub:"todo"},{expand:"str"},{type:"str",match:/(>|\|)\r?\n((\s[^\n]*)?(\r?\n|$))*/g},{type:"type",match:/!![a-z]+/g},{type:"bool",match:/\b(Yes|No)\b/g},{type:"oper",match:/[+:-]/g},{expand:"num"},{type:"var",match:/[a-zA-Z]\w*(?=:)/g}]});var U={num:{type:"num",match:/(\.e?|\b)\d(e-|[\d.oxa-fA-F_])*(\.|\b)/g},str:{type:"str",match:/(["'])(\\[^]|(?!\1)[^\r\n\\])*\1?/g},strDouble:{type:"str",match:/"((?!")[^\r\n\\]|\\[^])*"?/g}};var Se=w({"./languages/asm.js":()=>Promise.resolve().then(()=>(F(),P)),"./languages/bash.js":()=>Promise.resolve().then(()=>(f(),$)),"./languages/bf.js":()=>Promise.resolve().then(()=>(B(),v)),"./languages/c.js":()=>Promise.resolve().then(()=>(H(),G)),"./languages/css.js":()=>Promise.resolve().then(()=>(z(),k)),"./languages/csv.js":()=>Promise.resolve().then(()=>(Y(),_)),"./languages/diff.js":()=>Promise.resolve().then(()=>(N(),Z)),"./languages/docker.js":()=>Promise.resolve().then(()=>(W(),X)),"./languages/git.js":()=>Promise.resolve().then(()=>(K(),j)),"./languages/go.js":()=>Promise.resolve().then(()=>(q(),V)),"./languages/html.js":()=>Promise.resolve().then(()=>(et(),tt)),"./languages/http.js":()=>Promise.resolve().then(()=>(pt(),at)),"./languages/ini.js":()=>Promise.resolve().then(()=>(ct(),st)),"./languages/java.js":()=>Promise.resolve().then(()=>(mt(),nt)),"./languages/js.js":()=>Promise.resolve().then(()=>(L(),rt)),"./languages/js_template_literals.js":()=>Promise.resolve().then(()=>(Et(),ot)),"./languages/jsdoc.js":()=>Promise.resolve().then(()=>(ht(),ut)),"./languages/json.js":()=>Promise.resolve().then(()=>(gt(),it)),"./languages/leanpub-md.js":()=>Promise.resolve().then(()=>(yt(),bt)),"./languages/log.js":()=>Promise.resolve().then(()=>(ft(),Tt)),"./languages/lua.js":()=>Promise.resolve().then(()=>(Nt(),It)),"./languages/make.js":()=>Promise.resolve().then(()=>(Rt(),At)),"./languages/md.js":()=>Promise.resolve().then(()=>(D(),dt)),"./languages/pl.js":()=>Promise.resolve().then(()=>(Lt(),Ot)),"./languages/plain.js":()=>Promise.resolve().then(()=>(St(),xt)),"./languages/py.js":()=>Promise.resolve().then(()=>(Dt(),Ct)),"./languages/regex.js":()=>Promise.resolve().then(()=>(Ut(),wt)),"./languages/rs.js":()=>Promise.resolve().then(()=>(Ft(),Pt)),"./languages/sql.js":()=>Promise.resolve().then(()=>($t(),Mt)),"./languages/todo.js":()=>Promise.resolve().then(()=>(S(),lt)),"./languages/toml.js":()=>Promise.resolve().then(()=>(Bt(),vt)),"./languages/ts.js":()=>Promise.resolve().then(()=>(Ht(),Gt)),"./languages/uri.js":()=>Promise.resolve().then(()=>(zt(),kt)),"./languages/xml.js":()=>Promise.resolve().then(()=>(R(),J)),"./languages/yaml.js":()=>Promise.resolve().then(()=>(Yt(),_t))});var b={},Ce=(t="")=>t.replaceAll("&","&").replaceAll?.("<","<").replaceAll?.(">",">"),De=(t,e)=>e?`<span class="shj-syn-${e}">${t}</span>`:t;async function Zt(t,e,s){try{let c,m,n={},i,r=[],h=0,y=typeof e=="string"?await(b[e]??(b[e]=Se(`./languages/${e}.js`))):e,g=[...typeof e=="string"?y.default:e.sub];for(;h<t.length;){for(n.index=null,c=g.length;c-- >0;){if(m=g[c].expand?U[g[c].expand]:g[c],r[c]===void 0||r[c].match.index<h){if(m.match.lastIndex=h,i=m.match.exec(t),i===null){g.splice(c,1),r.splice(c,1);continue}r[c]={match:i,lastIndex:m.match.lastIndex}}r[c].match[0]&&(r[c].match.index<=n.index||n.index===null)&&(n={part:m,index:r[c].match.index,match:r[c].match[0],end:r[c].lastIndex})}if(n.index===null)break;s(t.slice(h,n.index),y.type),h=n.end,n.part.sub?await Zt(n.match,typeof n.part.sub=="string"?n.part.sub:typeof n.part.sub=="function"?n.part.sub(n.match):n.part,s):s(n.match,n.part.type)}s(t.slice(h,t.length),y.type)}catch{s(t)}}async function we(t,e,s=!0,c={}){let m="";return await Zt(t,e,(n,i)=>m+=De(Ce(n),i)),s?`<div><div class="shj-numbers">${"<div></div>".repeat(!c.hideLineNumbers&&t.split(` | ||
| `)[0].slice(3)||u(t)}]})},{type:"str",match:/`[^`]*`/g},{type:"var",match:/~~((?!~~).)*~~/g},{type:"kwd",match:/\b_\S([^\n]*?\S)?_\b|\*\S([^\n]*?\S)?\*/g},{type:"kwd",match:/^\s*(\*|\d+\.)\s/gm},{type:"func",match:/\[[^\]]*]\([^)]*\)|<[^>]*>/g,sub:[{type:"oper",match:/^\[[^\]]*]/g}]}]});var bt={};p(bt,{default:()=>he});var he,yt=a(()=>{D();d();he=[{type:"insert",match:/(leanpub-start-insert)((?!leanpub-end-insert)[^])*(leanpub-end-insert)?/g,sub:[{type:"insert",match:/leanpub-(start|end)-insert/g},{match:/(?!leanpub-start-insert)((?!leanpub-end-insert)[^])*/g,sub:u}]},{type:"deleted",match:/(leanpub-start-delete)((?!leanpub-end-delete)[^])*(leanpub-end-delete)?/g,sub:[{type:"deleted",match:/leanpub-(start|end)-delete/g},{match:/(?!leanpub-start-delete)((?!leanpub-end-delete)[^])*/g,sub:u}]},...C]});var Tt={};p(Tt,{default:()=>ie});var ie,ft=a(()=>{ie=[{type:"cmnt",match:/^#.*/gm},{expand:"strDouble"},{expand:"num"},{type:"err",match:/\b(err(or)?|[a-z_-]*exception|warn|warning|failed|ko|invalid|not ?found|alert|fatal)\b/gi},{type:"num",match:/\b(null|undefined)\b/gi},{type:"bool",match:/\b(false|true|yes|no)\b/gi},{type:"oper",match:/\.|,/g}]});var It={};p(It,{default:()=>ge});var ge,Nt=a(()=>{ge=[{match:/^#!.*|--(\[(=*)\[((?!--\]\2\])[^])*--\]\2\]|.*)/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/\b(and|break|do|else|elseif|end|for|function|if|in|local|not|or|repeat|return|then|until|while)\b/g},{type:"bool",match:/\b(true|false|nil)\b/g},{type:"oper",match:/[+*/%^#=~<>:,.-]+/g},{expand:"num"},{type:"func",match:/[a-z_]+(?=\s*[({])/g}]});var At={};p(At,{default:()=>de});var de,Rt=a(()=>{de=[{match:/^\s*#.*/gm,sub:"todo"},{expand:"str"},{type:"oper",match:/[${}()]+/g},{type:"class",match:/.PHONY:/gm},{type:"section",match:/^[\w.]+:/gm},{type:"kwd",match:/\b(ifneq|endif)\b/g},{expand:"num"},{type:"var",match:/[A-Z_]+(?=\s*=)/g},{match:/^.*$/gm,sub:"bash"}]});var Ot={};p(Ot,{default:()=>be});var be,Lt=a(()=>{be=[{match:/#.*/g,sub:"todo"},{type:"str",match:/(["'])(\\[^]|(?!\1)[^])*\1?/g},{expand:"num"},{type:"kwd",match:/\b(any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|return|say|state|sub|switch|undef|unless|until|use|when|while|not|and|or|xor)\b/g},{type:"oper",match:/[-+*/%~!&<>|=?,]+/g},{type:"func",match:/[a-z_]+(?=\s*\()/g}]});var xt={};p(xt,{default:()=>ye});var ye,St=a(()=>{ye=[{expand:"strDouble"}]});var Ct={};p(Ct,{default:()=>Te});var Te,Dt=a(()=>{Te=[{match:/#.*/g,sub:"todo"},{type:"str",match:/f("""|''')(\\[^]|(?!\1)[^])*\1?|f("|')(\\[^]|(?!\3).)*\3?/gi,sub:[{type:"var",match:/{[^{}]*}/g,sub:[{match:/(?!^{)[^]*(?=}$)/g,sub:"py"}]}]},{match:/("""|''')(\\[^]|(?!\1)[^])*\1?/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/\b(and|as|assert|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/g},{type:"bool",match:/\b(False|True|None)\b/g},{expand:"num"},{type:"func",match:/[a-z_]\w*(?=\s*\()/gi},{type:"oper",match:/[-/*+<>,=!&|^%]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var wt={};p(wt,{default:()=>fe,type:()=>Ie});var fe,Ie,Ut=a(()=>{fe=[{match:/^(?!\/).*/gm,sub:"todo"},{type:"num",match:/\[((?!\])[^\\]|\\.)*\]/g},{type:"kwd",match:/\||\^|\$|\\.|\w+($|\r|\n)/g},{type:"var",match:/\*|\+|\{\d+,\d+\}/g}],Ie="oper"});var Pt={};p(Pt,{default:()=>Ne});var Ne,Ft=a(()=>{Ne=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(as|break|const|continue|crate|else|enum|extern|false|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|true|type|unsafe|use|where|while|async|await|dyn|abstract|become|box|do|final|macro|override|priv|typeof|unsized|virtual|yield|try)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*!?\s*\()/g}]});var Mt={};p(Mt,{default:()=>Ae});var Ae,$t=a(()=>{Ae=[{match:/--.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"func",match:/\b(AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/g},{type:"kwd",match:/\b(ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|kwdS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:S|ING)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/g},{type:"num",match:/\.?\d[\d.oxa-fA-F-]*|\bNULL\b/g},{type:"bool",match:/\b(TRUE|FALSE)\b/g},{type:"oper",match:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|IN|ILIKE|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/g},{type:"var",match:/@\S+/g}]});var vt={};p(vt,{default:()=>Re});var Re,Bt=a(()=>{Re=[{match:/#.*/g,sub:"todo"},{type:"str",match:/("""|''')((?!\1)[^]|\\[^])*\1?/g},{expand:"str"},{type:"section",match:/^\[.+\]\s*$/gm},{type:"num",match:/\b(inf|nan)\b|\d[\d:ZT.-]*/g},{expand:"num"},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[+,.=-]/g},{type:"var",match:/\w+(?= \=)/g}]});var Gt={};p(Gt,{default:()=>Oe});var Oe,Ht=a(()=>{L();Oe=[{type:"type",match:/:\s*(any|void|number|boolean|string|object|never|enum)\b/g},{type:"kwd",match:/\b(type|namespace|typedef|interface|public|private|protected|implements|declare|abstract|readonly)\b/g},...O]});var kt={};p(kt,{default:()=>Le});var Le,zt=a(()=>{Le=[{match:/^#.*/gm,sub:"todo"},{type:"class",match:/^\w+(?=:?)/gm},{type:"num",match:/:\d+/g},{type:"oper",match:/[:/&?]|\w+=/g},{type:"func",match:/[.\w]+@|#[\w]+$/gm},{type:"var",match:/\w+\.\w+(\.\w+)*/g}]});var _t={};p(_t,{default:()=>xe});var xe,Yt=a(()=>{xe=[{match:/#.*/g,sub:"todo"},{expand:"str"},{type:"str",match:/(>|\|)\r?\n((\s[^\n]*)?(\r?\n|$))*/g},{type:"type",match:/!![a-z]+/g},{type:"bool",match:/\b(Yes|No)\b/g},{type:"oper",match:/[+:-]/g},{expand:"num"},{type:"var",match:/[a-zA-Z]\w*(?=:)/g}]});var U={num:{type:"num",match:/(\.e?|\b)\d(e-|[\d.oxa-fA-F_])*(\.|\b)/g},str:{type:"str",match:/(["'])(\\[^]|(?!\1)[^\r\n\\])*\1?/g},strDouble:{type:"str",match:/"((?!")[^\r\n\\]|\\[^])*"?/g}};var Se=w({"./languages/asm.js":()=>Promise.resolve().then(()=>(F(),P)),"./languages/bash.js":()=>Promise.resolve().then(()=>(f(),$)),"./languages/bf.js":()=>Promise.resolve().then(()=>(B(),v)),"./languages/c.js":()=>Promise.resolve().then(()=>(H(),G)),"./languages/css.js":()=>Promise.resolve().then(()=>(z(),k)),"./languages/csv.js":()=>Promise.resolve().then(()=>(Y(),_)),"./languages/diff.js":()=>Promise.resolve().then(()=>(N(),Z)),"./languages/docker.js":()=>Promise.resolve().then(()=>(W(),X)),"./languages/git.js":()=>Promise.resolve().then(()=>(K(),j)),"./languages/go.js":()=>Promise.resolve().then(()=>(q(),V)),"./languages/html.js":()=>Promise.resolve().then(()=>(et(),tt)),"./languages/http.js":()=>Promise.resolve().then(()=>(pt(),at)),"./languages/ini.js":()=>Promise.resolve().then(()=>(ct(),st)),"./languages/java.js":()=>Promise.resolve().then(()=>(mt(),nt)),"./languages/js.js":()=>Promise.resolve().then(()=>(L(),rt)),"./languages/js_template_literals.js":()=>Promise.resolve().then(()=>(Et(),ot)),"./languages/jsdoc.js":()=>Promise.resolve().then(()=>(ht(),ut)),"./languages/json.js":()=>Promise.resolve().then(()=>(gt(),it)),"./languages/leanpub-md.js":()=>Promise.resolve().then(()=>(yt(),bt)),"./languages/log.js":()=>Promise.resolve().then(()=>(ft(),Tt)),"./languages/lua.js":()=>Promise.resolve().then(()=>(Nt(),It)),"./languages/make.js":()=>Promise.resolve().then(()=>(Rt(),At)),"./languages/md.js":()=>Promise.resolve().then(()=>(D(),dt)),"./languages/pl.js":()=>Promise.resolve().then(()=>(Lt(),Ot)),"./languages/plain.js":()=>Promise.resolve().then(()=>(St(),xt)),"./languages/py.js":()=>Promise.resolve().then(()=>(Dt(),Ct)),"./languages/regex.js":()=>Promise.resolve().then(()=>(Ut(),wt)),"./languages/rs.js":()=>Promise.resolve().then(()=>(Ft(),Pt)),"./languages/sql.js":()=>Promise.resolve().then(()=>($t(),Mt)),"./languages/todo.js":()=>Promise.resolve().then(()=>(S(),lt)),"./languages/toml.js":()=>Promise.resolve().then(()=>(Bt(),vt)),"./languages/ts.js":()=>Promise.resolve().then(()=>(Ht(),Gt)),"./languages/uri.js":()=>Promise.resolve().then(()=>(zt(),kt)),"./languages/xml.js":()=>Promise.resolve().then(()=>(R(),J)),"./languages/yaml.js":()=>Promise.resolve().then(()=>(Yt(),_t))});var b={},Ce=(t="")=>t.replaceAll("&","&").replaceAll?.("<","<").replaceAll?.(">",">"),De=(t,e)=>e?`<span class="shj-syn-${e}">${t}</span>`:t;async function Zt(t,e,s){try{let c,m,n={},i,r=[],h=0,y=typeof e=="string"?await(b[e]??(b[e]=Se(`./languages/${e}.js`))):e,g=[...typeof e=="string"?y.default:e.sub];for(;h<t.length;){for(n.index=null,c=g.length;c-- >0;){if(m=g[c].expand?U[g[c].expand]:g[c],r[c]===void 0||r[c].match.index<h){if(m.match.lastIndex=h,i=m.match.exec(t),i===null){g.splice(c,1),r.splice(c,1);continue}r[c]={match:i,lastIndex:m.match.lastIndex}}r[c].match[0]&&(r[c].match.index<=n.index||n.index===null)&&(n={part:m,index:r[c].match.index,match:r[c].match[0],end:r[c].lastIndex})}if(n.index===null)break;s(t.slice(h,n.index),y.type),h=n.end,n.part.sub?await Zt(n.match,typeof n.part.sub=="string"?n.part.sub:typeof n.part.sub=="function"?n.part.sub(n.match):n.part,s):s(n.match,n.part.type)}s(t.slice(h,t.length),y.type)}catch{s(t)}}async function we(t,e,s=!0,c={}){let m="";return await Zt(t,e,(n,i)=>m+=De(Ce(n),i)),s?`<div><div class="shj-numbers">${"<div></div>".repeat(!c.hideLineNumbers&&t.split(` | ||
| `).length)}</div><div>${m}</div></div>`:m}async function Ue(t,e=t.className.match(/shj-lang-([\w-]+)/)?.[1],s,c){let m=t.textContent;s??(s=`${t.tagName=="CODE"?"in":m.split(` | ||
| `).length<2?"one":"multi"}line`),t.dataset.lang=e,t.className=`${[...t.classList].filter(n=>!n.startsWith("shj-")).join(" ")} shj-lang-${e} shj-${s}`,t.innerHTML=await we(m,e,s=="multiline",c)}var Ke=async t=>Promise.all(Array.from(document.querySelectorAll('[class*="shj-lang-"]')).map(e=>Ue(e,void 0,void 0,t))),Ve=(t,e)=>{b[t]=e};export{Ke as highlightAll,Ue as highlightElement,we as highlightText,Ve as loadLanguage,Zt as tokenize}; |
| var te=Object.defineProperty;var d=n=>t=>{var s=n[t];if(s)return s();throw new Error("Module not found in bundle: "+t)};var e=(n,t)=>()=>(n&&(t=n(n=0)),t);var a=(n,t)=>{for(var s in t)te(n,s,{get:t[s],enumerable:!0})};var B={};a(B,{default:()=>ee});var ee,G=e(()=>{ee=[{type:"cmnt",match:/(;|#).*/gm},{expand:"str"},{expand:"num"},{type:"num",match:/\$[\da-fA-F]*\b/g},{type:"kwd",match:/^[a-z]+\s+[a-z.]+\b/gm,sub:[{type:"func",match:/^[a-z]+/g}]},{type:"kwd",match:/^\t*[a-z][a-z\d]*\b/gm},{match:/%|\$/g,type:"oper"}]});var H={};a(H,{default:()=>I});var k,I,N=e(()=>{k={type:"var",match:/\$\w+|\${[^}]*}|\$\([^)]*\)/g},I=[{sub:"todo",match:/#.*/g},{type:"str",match:/(["'])((?!\1)[^\r\n\\]|\\[^])*\1?/g,sub:[k]},{type:"oper",match:/(?<=\s|^)\.*\/[a-z/_.-]+/gi},{type:"kwd",match:/\s-[a-zA-Z]+|$<|[&|;]+|\b(unset|readonly|shift|export|if|fi|else|elif|while|do|done|for|until|case|esac|break|continue|exit|return|trap|wait|eval|exec|then|declare|enable|local|select|typeset|time|add|remove|install|update|delete)(?=\s|$)/g},{expand:"num"},{type:"func",match:/(?<=(^|\||\&\&|\;)\s*)[a-z_.-]+(?=\s|$)/gmi},{type:"bool",match:/(?<=\s|^)(true|false)(?=\s|$)/g},{type:"oper",match:/[=(){}<>!]+/g},{type:"var",match:/(?<=\s|^)[\w_]+(?=\s*=)/g},k]});var z={};a(z,{default:()=>ae});var ae,_=e(()=>{ae=[{match:/[^\[\->+.<\]\s].*/g,sub:"todo"},{type:"func",match:/\.+/g},{type:"kwd",match:/[<>]+/g},{type:"oper",match:/[+-]+/g}]});var Y={};a(Y,{default:()=>ne});var ne,Z=e(()=>{ne=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/#\s*include (<.*>|".*")/g,sub:[{type:"str",match:/(<|").*/g}]},{match:/asm\s*{[^}]*}/g,sub:[{type:"kwd",match:/^asm/g},{match:/[^{}]*(?=}$)/g,sub:"asm"}]},{type:"kwd",match:/\*|&|#[a-z]+\b|\b(asm|auto|double|int|struct|break|else|long|switch|case|enum|register|typedef|char|extern|return|union|const|float|short|unsigned|continue|for|signed|void|default|goto|sizeof|volatile|do|if|static|while)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var X={};a(X,{default:()=>pe});var pe,W=e(()=>{pe=[{match:/\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/@\w+\b|\b(and|not|only|or)\b|\b[a-z-]+(?=[^{}]*{)/g},{type:"var",match:/\b[\w-]+(?=\s*:)|(::?|\.)[\w-]+(?=[^{}]*{)/g},{type:"func",match:/#[\w-]+(?=[^{}]*{)/g},{type:"num",match:/#[\da-f]{3,8}/g},{type:"num",match:/\d+(\.\d+)?(cm|mm|in|px|pt|pc|em|ex|ch|rem|vm|vh|vmin|vmax|%)?/g,sub:[{type:"var",match:/[a-z]+|%/g}]},{match:/url\([^)]*\)/g,sub:[{type:"func",match:/url(?=\()/g},{type:"str",match:/[^()]+/g}]},{type:"func",match:/\b[a-zA-Z]\w*(?=\s*\()/g},{type:"num",match:/\b[a-z-]+\b/g}]});var j={};a(j,{default:()=>se});var se,K=e(()=>{se=[{expand:"strDouble"},{type:"oper",match:/,/g}]});var V={};a(V,{default:()=>A});var A,R=e(()=>{A=[{type:"deleted",match:/^[-<].*/gm},{type:"insert",match:/^[+>].*/gm},{type:"kwd",match:/!.*/gm},{type:"section",match:/^@@.*@@$|^\d.*|^([*-+])\1\1.*/gm}]});var q={};a(q,{default:()=>re});var re,Q=e(()=>{N();re=[{type:"kwd",match:/^(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)\b/gmi},...I]});var J={};a(J,{default:()=>ce});var ce,tt=e(()=>{R();ce=[{match:/^#.*/gm,sub:"todo"},{expand:"str"},...A,{type:"func",match:/^(\$ )?git(\s.*)?$/gm},{type:"kwd",match:/^commit \w+$/gm}]});var et={};a(et,{default:()=>me});var me,at=e(()=>{me=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\*|&|\b(break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go|goto|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"oper",match:/[+\-*\/%&|^~=!<>.^-]+/g}]});var pt={};a(pt,{default:()=>O,name:()=>u,properties:()=>E,xmlElement:()=>l});var nt,oe,u,E,l,O,x=e(()=>{nt=":A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD",oe=nt+"\\-\\.0-9\xB7\u0300-\u036F\u203F-\u2040",u=`[${nt}][${oe}]*`,E=`\\s*(\\s+${u}\\s*(=\\s*([^"']\\S*|("|')(\\\\[^]|(?!\\4)[^])*\\4?)?)?\\s*)*`,l={match:RegExp(`<[/!?]?${u}${E}[/!?]?>`,"g"),sub:[{type:"var",match:RegExp(`^<[/!?]?${u}`,"g"),sub:[{type:"oper",match:/^<[\/!?]?/g}]},{type:"str",match:/=\s*([^"']\S*|("|')(\\[^]|(?!\2)[^])*\2?)/g,sub:[{type:"oper",match:/^=/g}]},{type:"oper",match:/[\/!?]?>/g},{type:"class",match:RegExp(u,"g")}]},O=[{match:/<!--((?!-->)[^])*-->/g,sub:"todo"},{type:"class",match:/<!\[CDATA\[[\s\S]*?\]\]>/gi},l,{type:"str",match:RegExp(`<\\?${u}([^?]|\\?[^?>])*\\?+>`,"g"),sub:[{type:"var",match:RegExp(`^<\\?${u}`,"g"),sub:[{type:"oper",match:/^<\?/g}]},{type:"oper",match:/\?+>$/g}]},{type:"var",match:/&(#x?)?[\da-z]{1,8};/gi}]});var st={};a(st,{default:()=>le});var le,rt=e(()=>{x();le=[{type:"class",match:/<!DOCTYPE("[^"]*"|'[^']*'|[^"'>])*>/gi,sub:[{type:"str",match:/"[^"]*"|'[^']*'/g},{type:"oper",match:/^<!|>$/g},{type:"var",match:/DOCTYPE/gi}]},{match:RegExp(`<style${E}>((?!</style>)[^])*</style\\s*>`,"g"),sub:[{match:RegExp(`^<style${E}>`,"g"),sub:l.sub},{match:RegExp(`${l.match}|[^]*(?=</style\\s*>$)`,"g"),sub:"css"},l]},{match:RegExp(`<script${E}>((?!<\/script>)[^])*<\/script\\s*>`,"g"),sub:[{match:RegExp(`^<script${E}>`,"g"),sub:l.sub},{match:RegExp(`${l.match}|[^]*(?=<\/script\\s*>$)`,"g"),sub:"js"},l]},...O]});var ue,i,b=e(()=>{ue=[["bash",[/#!(\/usr)?\/bin\/bash/g,500],[/\b(if|elif|then|fi|echo)\b|\$/g,10]],["html",[/<\/?[a-z-]+[^\n>]*>/g,10],[/^\s+<!DOCTYPE\s+html/g,500]],["http",[/^(GET|HEAD|POST|PUT|DELETE|PATCH|HTTP)\b/g,500]],["js",[/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require)\b/g,10]],["ts",[/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require|implements|interface|namespace)\b/g,10]],["py",[/\b(def|print|class|and|or|lambda)\b/g,10]],["sql",[/\b(SELECT|INSERT|FROM)\b/g,50]],["pl",[/#!(\/usr)?\/bin\/perl/g,500],[/\b(use|print)\b|\$/g,10]],["lua",[/#!(\/usr)?\/bin\/lua/g,500]],["make",[/\b(ifneq|endif|if|elif|then|fi|echo|.PHONY|^[a-z]+ ?:$)\b|\$/gm,10]],["uri",[/https?:|mailto:|tel:|ftp:/g,30]],["css",[/^(@import|@page|@media|(\.|#)[a-z]+)/gm,20]],["diff",[/^[+><-]/gm,10],[/^@@ ?[-+,0-9 ]+ ?@@/gm,25]],["md",[/^(>|\t\*|\t\d+.)/gm,10],[/\[.*\](.*)/g,10]],["docker",[/^(FROM|ENTRYPOINT|RUN)/gm,500]],["xml",[/<\/?[a-z-]+[^\n>]*>/g,10],[/^<\?xml/g,500]],["c",[/#include\b|\bprintf\s+\(/g,100]],["rs",[/^\s+(use|fn|mut|match)\b/gm,100]],["go",[/\b(func|fmt|package)\b/g,100]],["java",[/^import\s+java/gm,500]],["asm",[/^(section|global main|extern|\t(call|mov|ret))/gm,100]],["css",[/^(@import|@page|@media|(\.|#)[a-z]+)/gm,20]],["json",[/\b(true|false|null|\{})\b|\"[^"]+\":/g,10]],["yaml",[/^(\s+)?[a-z][a-z0-9]*:/gmi,10]]],i=n=>ue.map(([t,...s])=>[t,s.reduce((r,[m,c])=>r+[...n.matchAll(m)].length*c,0)]).filter(([t,s])=>s>20).sort((t,s)=>s[1]-t[1])[0]?.[0]||"plain"});var ct={};a(ct,{default:()=>Ee});var Ee,mt=e(()=>{b();Ee=[{type:"kwd",match:/^(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI|SEARCH)\b/gm},{expand:"str"},{type:"section",match:/\bHTTP\/[\d.]+\b/g},{expand:"num"},{type:"oper",match:/[,;:=]/g},{type:"var",match:/[a-zA-Z][\w-]*(?=:)/g},{match:/\n\n[^]*/g,sub:i}]});var ot={};a(ot,{default:()=>ie});var ie,lt=e(()=>{ie=[{match:/(^[ \f\t\v]*)[#;].*/gm,sub:"todo"},{type:"str",match:/.*/g},{type:"var",match:/.*(?==)/g},{type:"section",match:/^\s*\[.+\]\s*$/gm},{type:"oper",match:/=/g}]});var ut={};a(ut,{default:()=>he});var he,Et=e(()=>{he=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(abstract|assert|boolean|break|byte|case|catch|char|class|continue|const|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|package|private|protected|public|requires|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|transient|try|var|void|volatile|while)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*\()/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var it={};a(it,{default:()=>L});var L,S=e(()=>{L=[{match:/\/\*\*((?!\*\/)[^])*(\*\/)?/g,sub:"jsdoc"},{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{match:/`((?!`)[^]|\\[^])*`?/g,sub:"js_template_literals"},{type:"kwd",match:/=>|\b(this|set|get|as|async|await|break|case|catch|class|const|constructor|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|if|implements|import|in|instanceof|interface|let|var|of|new|package|private|protected|public|return|static|super|switch|throw|throws|try|typeof|void|while|with|yield)\b/g},{match:/\/((?!\/)[^\r\n\\]|\\.)+\/[dgimsuy]*/g,sub:"regex"},{expand:"num"},{type:"num",match:/\b(NaN|null|undefined|[A-Z][A-Z_]*)\b/g},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z$_][\w$_]*(?=\s*((\?\.)?\s*\(|=\s*(\(?[\w,{}\[\])]+\)? =>|function\b)))/g}]});var ht={};a(ht,{default:()=>ge,type:()=>de});var ge,de,gt=e(()=>{ge=[{match:new class{exec(n){let t=this.lastIndex,s,r=m=>{for(;++t<n.length-2;)if(n[t]=="{")r();else if(n[t]=="}")return};for(;t<n.length;++t)if(n[t-1]!="\\"&&n[t]=="$"&&n[t+1]=="{")return s=t++,r(t),this.lastIndex=t+1,{index:s,0:n.slice(s,t+1)};return null}},sub:[{type:"kwd",match:/^\${|}$/g},{match:/(?!^\$|{)[^]+(?=}$)/g,sub:"js"}]}],de="str"});var dt={};a(dt,{default:()=>C,type:()=>be});var C,be,D=e(()=>{C=[{type:"err",match:/\b(TODO|FIXME|DEBUG|OPTIMIZE|WARNING|XXX|BUG)\b/g},{type:"class",match:/\bIDEA\b/g},{type:"insert",match:/\b(CHANGED|FIX|CHANGE)\b/g},{type:"oper",match:/\bQUESTION\b/g}],be="cmnt"});var bt={};a(bt,{default:()=>ye,type:()=>Te});var ye,Te,yt=e(()=>{D();ye=[{type:"kwd",match:/@\w+/g},{type:"class",match:/{[\w\s|<>,.@\[\]]+}/g},{type:"var",match:/\[[\w\s="']+\]/g},...C],Te="cmnt"});var Tt={};a(Tt,{default:()=>fe});var fe,ft=e(()=>{fe=[{type:"var",match:/(("|')((?!\2)[^\r\n\\]|\\[^])*\2|[a-zA-Z]\w*)(?=\s*:)/g},{expand:"str"},{expand:"num"},{type:"num",match:/\bnull\b/g},{type:"bool",match:/\b(true|false)\b/g}]});var It={};a(It,{default:()=>w});var w,U=e(()=>{b();w=[{type:"cmnt",match:/^>.*|(=|-)\1+/gm},{type:"class",match:/\*\*((?!\*\*).)*\*\*/g},{match:/```((?!```)[^])*\n```/g,sub:n=>({type:"kwd",sub:[{match:/\n[^]*(?=```)/g,sub:n.split(` | ||
| `)[0].slice(3)||i(n)}]})},{type:"str",match:/`[^`]*`/g},{type:"var",match:/~~((?!~~).)*~~/g},{type:"kwd",match:/\b_\S([^\n]*?\S)?_\b|\*\S([^\n]*?\S)?\*/g},{type:"kwd",match:/^\s*(\*|\d+\.)\s/gm},{type:"func",match:/\[[^\]]*]\([^)]*\)|<[^>]*>/g,sub:[{type:"oper",match:/^\[[^\]]*]/g}]}]});var Nt={};a(Nt,{default:()=>Ie});var Ie,At=e(()=>{U();b();Ie=[{type:"insert",match:/(leanpub-start-insert)((?!leanpub-end-insert)[^])*(leanpub-end-insert)?/g,sub:[{type:"insert",match:/leanpub-(start|end)-insert/g},{match:/(?!leanpub-start-insert)((?!leanpub-end-insert)[^])*/g,sub:i}]},{type:"deleted",match:/(leanpub-start-delete)((?!leanpub-end-delete)[^])*(leanpub-end-delete)?/g,sub:[{type:"deleted",match:/leanpub-(start|end)-delete/g},{match:/(?!leanpub-start-delete)((?!leanpub-end-delete)[^])*/g,sub:i}]},...w]});var Rt={};a(Rt,{default:()=>Ne});var Ne,Ot=e(()=>{Ne=[{type:"cmnt",match:/^#.*/gm},{expand:"strDouble"},{expand:"num"},{type:"err",match:/\b(err(or)?|[a-z_-]*exception|warn|warning|failed|ko|invalid|not ?found|alert|fatal)\b/gi},{type:"num",match:/\b(null|undefined)\b/gi},{type:"bool",match:/\b(false|true|yes|no)\b/gi},{type:"oper",match:/\.|,/g}]});var xt={};a(xt,{default:()=>Ae});var Ae,Lt=e(()=>{Ae=[{match:/^#!.*|--(\[(=*)\[((?!--\]\2\])[^])*--\]\2\]|.*)/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/\b(and|break|do|else|elseif|end|for|function|if|in|local|not|or|repeat|return|then|until|while)\b/g},{type:"bool",match:/\b(true|false|nil)\b/g},{type:"oper",match:/[+*/%^#=~<>:,.-]+/g},{expand:"num"},{type:"func",match:/[a-z_]+(?=\s*[({])/g}]});var St={};a(St,{default:()=>Re});var Re,Ct=e(()=>{Re=[{match:/^\s*#.*/gm,sub:"todo"},{expand:"str"},{type:"oper",match:/[${}()]+/g},{type:"class",match:/.PHONY:/gm},{type:"section",match:/^[\w.]+:/gm},{type:"kwd",match:/\b(ifneq|endif)\b/g},{expand:"num"},{type:"var",match:/[A-Z_]+(?=\s*=)/g},{match:/^.*$/gm,sub:"bash"}]});var Dt={};a(Dt,{default:()=>Oe});var Oe,wt=e(()=>{Oe=[{match:/#.*/g,sub:"todo"},{type:"str",match:/(["'])(\\[^]|(?!\1)[^])*\1?/g},{expand:"num"},{type:"kwd",match:/\b(any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|return|say|state|sub|switch|undef|unless|until|use|when|while|not|and|or|xor)\b/g},{type:"oper",match:/[-+*/%~!&<>|=?,]+/g},{type:"func",match:/[a-z_]+(?=\s*\()/g}]});var Ut={};a(Ut,{default:()=>xe});var xe,Pt=e(()=>{xe=[{expand:"strDouble"}]});var Ft={};a(Ft,{default:()=>Le});var Le,Mt=e(()=>{Le=[{match:/#.*/g,sub:"todo"},{match:/("""|''')(\\[^]|(?!\1)[^])*\1?/g,sub:"todo"},{type:"str",match:/f("|')(\\[^]|(?!\1).)*\1?|f((["'])\4\4)(\\[^]|(?!\3)[^])*\3?/gi,sub:[{type:"var",match:/{[^{}]*}/g,sub:[{match:/(?!^{)[^]*(?=}$)/g,sub:"py"}]}]},{expand:"str"},{type:"kwd",match:/\b(and|as|assert|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/g},{type:"bool",match:/\b(False|True|None)\b/g},{expand:"num"},{type:"func",match:/[a-z_]\w*(?=\s*\()/gi},{type:"oper",match:/[-/*+<>,=!&|^%]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var $t={};a($t,{default:()=>Se,type:()=>Ce});var Se,Ce,vt=e(()=>{Se=[{match:/^(?!\/).*/gm,sub:"todo"},{type:"num",match:/\[((?!\])[^\\]|\\.)*\]/g},{type:"kwd",match:/\||\^|\$|\\.|\w+($|\r|\n)/g},{type:"var",match:/\*|\+|\{\d+,\d+\}/g}],Ce="oper"});var Bt={};a(Bt,{default:()=>De});var De,Gt=e(()=>{De=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(as|break|const|continue|crate|else|enum|extern|false|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|true|type|unsafe|use|where|while|async|await|dyn|abstract|become|box|do|final|macro|override|priv|typeof|unsized|virtual|yield|try)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*!?\s*\()/g}]});var kt={};a(kt,{default:()=>we});var we,Ht=e(()=>{we=[{match:/--.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"func",match:/\b(AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/g},{type:"kwd",match:/\b(ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|kwdS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:S|ING)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/g},{type:"num",match:/\.?\d[\d.oxa-fA-F-]*|\bNULL\b/g},{type:"bool",match:/\b(TRUE|FALSE)\b/g},{type:"oper",match:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|IN|ILIKE|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/g},{type:"var",match:/@\S+/g}]});var zt={};a(zt,{default:()=>Ue});var Ue,_t=e(()=>{Ue=[{match:/#.*/g,sub:"todo"},{type:"str",match:/("""|''')((?!\1)[^]|\\[^])*\1?/g},{expand:"str"},{type:"section",match:/^\[.+\]\s*$/gm},{type:"num",match:/\b(inf|nan)\b|\d[\d:ZT.-]*/g},{expand:"num"},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[+,.=-]/g},{type:"var",match:/\w+(?= \=)/g}]});var Yt={};a(Yt,{default:()=>Pe});var Pe,Zt=e(()=>{S();Pe=[{type:"type",match:/:\s*(any|void|number|boolean|string|object|never|enum)\b/g},{type:"kwd",match:/\b(type|namespace|typedef|interface|public|private|protected|implements|declare|abstract|readonly)\b/g},...L]});var Xt={};a(Xt,{default:()=>Fe});var Fe,Wt=e(()=>{Fe=[{match:/^#.*/gm,sub:"todo"},{type:"class",match:/^\w+(?=:?)/gm},{type:"num",match:/:\d+/g},{type:"oper",match:/[:/&?]|\w+=/g},{type:"func",match:/[.\w]+@|#[\w]+$/gm},{type:"var",match:/\w+\.\w+(\.\w+)*/g}]});var jt={};a(jt,{default:()=>Me});var Me,Kt=e(()=>{Me=[{match:/#.*/g,sub:"todo"},{expand:"str"},{type:"str",match:/(>|\|)\r?\n((\s[^\n]*)?(\r?\n|$))*/g},{type:"type",match:/!![a-z]+/g},{type:"bool",match:/\b(Yes|No)\b/g},{type:"oper",match:/[+:-]/g},{expand:"num"},{type:"var",match:/[a-zA-Z]\w*(?=:)/g}]});var Vt={};a(Vt,{default:()=>p});var p,y=e(()=>{p={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",gray:"\x1B[90m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"}});var qt={};a(qt,{default:()=>ve});var ve,Qt=e(()=>{y();ve={deleted:p.red,var:p.red,err:p.red,kwd:p.magenta,num:p.yellow,class:p.yellow,cmnt:p.gray,insert:p.green,str:p.green,bool:p.cyan,type:p.blue,oper:p.blue,section:p.magenta,func:p.blue}});var M={};a(M,{default:()=>Be});var Be,$=e(()=>{y();Be={deleted:p.red,var:p.red,err:p.red,kwd:p.red,num:p.yellow,class:p.yellow,cmnt:p.gray,insert:p.green,str:p.green,bool:p.cyan,type:p.blue,oper:p.blue,section:p.magenta,func:p.magenta}});var v={num:{type:"num",match:/(\.e?|\b)\d(e-|[\d.oxa-fA-F_])*(\.|\b)/g},str:{type:"str",match:/(["'])(\\[^]|(?!\1)[^\r\n\\])*\1?/g},strDouble:{type:"str",match:/"((?!")[^\r\n\\]|\\[^])*"?/g}};var $e=d({"./languages/asm.js":()=>Promise.resolve().then(()=>(G(),B)),"./languages/bash.js":()=>Promise.resolve().then(()=>(N(),H)),"./languages/bf.js":()=>Promise.resolve().then(()=>(_(),z)),"./languages/c.js":()=>Promise.resolve().then(()=>(Z(),Y)),"./languages/css.js":()=>Promise.resolve().then(()=>(W(),X)),"./languages/csv.js":()=>Promise.resolve().then(()=>(K(),j)),"./languages/diff.js":()=>Promise.resolve().then(()=>(R(),V)),"./languages/docker.js":()=>Promise.resolve().then(()=>(Q(),q)),"./languages/git.js":()=>Promise.resolve().then(()=>(tt(),J)),"./languages/go.js":()=>Promise.resolve().then(()=>(at(),et)),"./languages/html.js":()=>Promise.resolve().then(()=>(rt(),st)),"./languages/http.js":()=>Promise.resolve().then(()=>(mt(),ct)),"./languages/ini.js":()=>Promise.resolve().then(()=>(lt(),ot)),"./languages/java.js":()=>Promise.resolve().then(()=>(Et(),ut)),"./languages/js.js":()=>Promise.resolve().then(()=>(S(),it)),"./languages/js_template_literals.js":()=>Promise.resolve().then(()=>(gt(),ht)),"./languages/jsdoc.js":()=>Promise.resolve().then(()=>(yt(),bt)),"./languages/json.js":()=>Promise.resolve().then(()=>(ft(),Tt)),"./languages/leanpub-md.js":()=>Promise.resolve().then(()=>(At(),Nt)),"./languages/log.js":()=>Promise.resolve().then(()=>(Ot(),Rt)),"./languages/lua.js":()=>Promise.resolve().then(()=>(Lt(),xt)),"./languages/make.js":()=>Promise.resolve().then(()=>(Ct(),St)),"./languages/md.js":()=>Promise.resolve().then(()=>(U(),It)),"./languages/pl.js":()=>Promise.resolve().then(()=>(wt(),Dt)),"./languages/plain.js":()=>Promise.resolve().then(()=>(Pt(),Ut)),"./languages/py.js":()=>Promise.resolve().then(()=>(Mt(),Ft)),"./languages/regex.js":()=>Promise.resolve().then(()=>(vt(),$t)),"./languages/rs.js":()=>Promise.resolve().then(()=>(Gt(),Bt)),"./languages/sql.js":()=>Promise.resolve().then(()=>(Ht(),kt)),"./languages/todo.js":()=>Promise.resolve().then(()=>(D(),dt)),"./languages/toml.js":()=>Promise.resolve().then(()=>(_t(),zt)),"./languages/ts.js":()=>Promise.resolve().then(()=>(Zt(),Yt)),"./languages/uri.js":()=>Promise.resolve().then(()=>(Wt(),Xt)),"./languages/xml.js":()=>Promise.resolve().then(()=>(x(),pt)),"./languages/yaml.js":()=>Promise.resolve().then(()=>(Kt(),jt))});var P={};async function F(n,t,s){try{let r,m,c={},T,o=[],h=0,f=typeof t=="string"?await(P[t]??(P[t]=$e(`./languages/${t}.js`))):t,g=[...typeof t=="string"?f.default:t.sub];for(;h<n.length;){for(c.index=null,r=g.length;r-- >0;){if(m=g[r].expand?v[g[r].expand]:g[r],o[r]===void 0||o[r].match.index<h){if(m.match.lastIndex=h,T=m.match.exec(n),T===null){g.splice(r,1),o.splice(r,1);continue}o[r]={match:T,lastIndex:m.match.lastIndex}}o[r].match[0]&&(o[r].match.index<=c.index||c.index===null)&&(c={part:m,index:o[r].match.index,match:o[r].match[0],end:o[r].lastIndex})}if(c.index===null)break;s(n.slice(h,c.index),f.type),h=c.end,c.part.sub?await F(c.match,typeof c.part.sub=="string"?c.part.sub:typeof c.part.sub=="function"?c.part.sub(c.match):c.part,s):s(c.match,c.part.type)}s(n.slice(h,n.length),f.type)}catch{s(n)}}var Ge=d({"./themes/atom-dark.js":()=>Promise.resolve().then(()=>(Qt(),qt)),"./themes/default.js":()=>Promise.resolve().then(()=>($(),M)),"./themes/termcolor.js":()=>Promise.resolve().then(()=>(y(),Vt))});var Jt=Promise.resolve().then(()=>($(),M)),ke=async(n,t)=>{let s="",r=(await Jt).default;return await F(n,t,(m,c)=>s+=c?`${r[c]??""}${m}\x1B[0m`:m),s},la=async(n,t)=>console.log(await ke(n,t)),ua=async n=>Jt=Ge(`./themes/${n}.js`);export{ke as highlightText,la as printHighlight,ua as setTheme}; | ||
| `)[0].slice(3)||i(n)}]})},{type:"str",match:/`[^`]*`/g},{type:"var",match:/~~((?!~~).)*~~/g},{type:"kwd",match:/\b_\S([^\n]*?\S)?_\b|\*\S([^\n]*?\S)?\*/g},{type:"kwd",match:/^\s*(\*|\d+\.)\s/gm},{type:"func",match:/\[[^\]]*]\([^)]*\)|<[^>]*>/g,sub:[{type:"oper",match:/^\[[^\]]*]/g}]}]});var Nt={};a(Nt,{default:()=>Ie});var Ie,At=e(()=>{U();b();Ie=[{type:"insert",match:/(leanpub-start-insert)((?!leanpub-end-insert)[^])*(leanpub-end-insert)?/g,sub:[{type:"insert",match:/leanpub-(start|end)-insert/g},{match:/(?!leanpub-start-insert)((?!leanpub-end-insert)[^])*/g,sub:i}]},{type:"deleted",match:/(leanpub-start-delete)((?!leanpub-end-delete)[^])*(leanpub-end-delete)?/g,sub:[{type:"deleted",match:/leanpub-(start|end)-delete/g},{match:/(?!leanpub-start-delete)((?!leanpub-end-delete)[^])*/g,sub:i}]},...w]});var Rt={};a(Rt,{default:()=>Ne});var Ne,Ot=e(()=>{Ne=[{type:"cmnt",match:/^#.*/gm},{expand:"strDouble"},{expand:"num"},{type:"err",match:/\b(err(or)?|[a-z_-]*exception|warn|warning|failed|ko|invalid|not ?found|alert|fatal)\b/gi},{type:"num",match:/\b(null|undefined)\b/gi},{type:"bool",match:/\b(false|true|yes|no)\b/gi},{type:"oper",match:/\.|,/g}]});var xt={};a(xt,{default:()=>Ae});var Ae,Lt=e(()=>{Ae=[{match:/^#!.*|--(\[(=*)\[((?!--\]\2\])[^])*--\]\2\]|.*)/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/\b(and|break|do|else|elseif|end|for|function|if|in|local|not|or|repeat|return|then|until|while)\b/g},{type:"bool",match:/\b(true|false|nil)\b/g},{type:"oper",match:/[+*/%^#=~<>:,.-]+/g},{expand:"num"},{type:"func",match:/[a-z_]+(?=\s*[({])/g}]});var St={};a(St,{default:()=>Re});var Re,Ct=e(()=>{Re=[{match:/^\s*#.*/gm,sub:"todo"},{expand:"str"},{type:"oper",match:/[${}()]+/g},{type:"class",match:/.PHONY:/gm},{type:"section",match:/^[\w.]+:/gm},{type:"kwd",match:/\b(ifneq|endif)\b/g},{expand:"num"},{type:"var",match:/[A-Z_]+(?=\s*=)/g},{match:/^.*$/gm,sub:"bash"}]});var Dt={};a(Dt,{default:()=>Oe});var Oe,wt=e(()=>{Oe=[{match:/#.*/g,sub:"todo"},{type:"str",match:/(["'])(\\[^]|(?!\1)[^])*\1?/g},{expand:"num"},{type:"kwd",match:/\b(any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|return|say|state|sub|switch|undef|unless|until|use|when|while|not|and|or|xor)\b/g},{type:"oper",match:/[-+*/%~!&<>|=?,]+/g},{type:"func",match:/[a-z_]+(?=\s*\()/g}]});var Ut={};a(Ut,{default:()=>xe});var xe,Pt=e(()=>{xe=[{expand:"strDouble"}]});var Ft={};a(Ft,{default:()=>Le});var Le,Mt=e(()=>{Le=[{match:/#.*/g,sub:"todo"},{type:"str",match:/f("""|''')(\\[^]|(?!\1)[^])*\1?|f("|')(\\[^]|(?!\3).)*\3?/gi,sub:[{type:"var",match:/{[^{}]*}/g,sub:[{match:/(?!^{)[^]*(?=}$)/g,sub:"py"}]}]},{match:/("""|''')(\\[^]|(?!\1)[^])*\1?/g,sub:"todo"},{expand:"str"},{type:"kwd",match:/\b(and|as|assert|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/g},{type:"bool",match:/\b(False|True|None)\b/g},{expand:"num"},{type:"func",match:/[a-z_]\w*(?=\s*\()/gi},{type:"oper",match:/[-/*+<>,=!&|^%]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g}]});var $t={};a($t,{default:()=>Se,type:()=>Ce});var Se,Ce,vt=e(()=>{Se=[{match:/^(?!\/).*/gm,sub:"todo"},{type:"num",match:/\[((?!\])[^\\]|\\.)*\]/g},{type:"kwd",match:/\||\^|\$|\\.|\w+($|\r|\n)/g},{type:"var",match:/\*|\+|\{\d+,\d+\}/g}],Ce="oper"});var Bt={};a(Bt,{default:()=>De});var De,Gt=e(()=>{De=[{match:/\/\/.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{expand:"num"},{type:"kwd",match:/\b(as|break|const|continue|crate|else|enum|extern|false|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|true|type|unsafe|use|where|while|async|await|dyn|abstract|become|box|do|final|macro|override|priv|typeof|unsized|virtual|yield|try)\b/g},{type:"oper",match:/[/*+:?&|%^~=!,<>.^-]+/g},{type:"class",match:/\b[A-Z][\w_]*\b/g},{type:"func",match:/[a-zA-Z_][\w_]*(?=\s*!?\s*\()/g}]});var kt={};a(kt,{default:()=>we});var we,Ht=e(()=>{we=[{match:/--.*\n?|\/\*((?!\*\/)[^])*(\*\/)?/g,sub:"todo"},{expand:"str"},{type:"func",match:/\b(AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/g},{type:"kwd",match:/\b(ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|kwdS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:S|ING)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/g},{type:"num",match:/\.?\d[\d.oxa-fA-F-]*|\bNULL\b/g},{type:"bool",match:/\b(TRUE|FALSE)\b/g},{type:"oper",match:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|IN|ILIKE|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/g},{type:"var",match:/@\S+/g}]});var zt={};a(zt,{default:()=>Ue});var Ue,_t=e(()=>{Ue=[{match:/#.*/g,sub:"todo"},{type:"str",match:/("""|''')((?!\1)[^]|\\[^])*\1?/g},{expand:"str"},{type:"section",match:/^\[.+\]\s*$/gm},{type:"num",match:/\b(inf|nan)\b|\d[\d:ZT.-]*/g},{expand:"num"},{type:"bool",match:/\b(true|false)\b/g},{type:"oper",match:/[+,.=-]/g},{type:"var",match:/\w+(?= \=)/g}]});var Yt={};a(Yt,{default:()=>Pe});var Pe,Zt=e(()=>{S();Pe=[{type:"type",match:/:\s*(any|void|number|boolean|string|object|never|enum)\b/g},{type:"kwd",match:/\b(type|namespace|typedef|interface|public|private|protected|implements|declare|abstract|readonly)\b/g},...L]});var Xt={};a(Xt,{default:()=>Fe});var Fe,Wt=e(()=>{Fe=[{match:/^#.*/gm,sub:"todo"},{type:"class",match:/^\w+(?=:?)/gm},{type:"num",match:/:\d+/g},{type:"oper",match:/[:/&?]|\w+=/g},{type:"func",match:/[.\w]+@|#[\w]+$/gm},{type:"var",match:/\w+\.\w+(\.\w+)*/g}]});var jt={};a(jt,{default:()=>Me});var Me,Kt=e(()=>{Me=[{match:/#.*/g,sub:"todo"},{expand:"str"},{type:"str",match:/(>|\|)\r?\n((\s[^\n]*)?(\r?\n|$))*/g},{type:"type",match:/!![a-z]+/g},{type:"bool",match:/\b(Yes|No)\b/g},{type:"oper",match:/[+:-]/g},{expand:"num"},{type:"var",match:/[a-zA-Z]\w*(?=:)/g}]});var Vt={};a(Vt,{default:()=>p});var p,y=e(()=>{p={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",gray:"\x1B[90m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"}});var qt={};a(qt,{default:()=>ve});var ve,Qt=e(()=>{y();ve={deleted:p.red,var:p.red,err:p.red,kwd:p.magenta,num:p.yellow,class:p.yellow,cmnt:p.gray,insert:p.green,str:p.green,bool:p.cyan,type:p.blue,oper:p.blue,section:p.magenta,func:p.blue}});var M={};a(M,{default:()=>Be});var Be,$=e(()=>{y();Be={deleted:p.red,var:p.red,err:p.red,kwd:p.red,num:p.yellow,class:p.yellow,cmnt:p.gray,insert:p.green,str:p.green,bool:p.cyan,type:p.blue,oper:p.blue,section:p.magenta,func:p.magenta}});var v={num:{type:"num",match:/(\.e?|\b)\d(e-|[\d.oxa-fA-F_])*(\.|\b)/g},str:{type:"str",match:/(["'])(\\[^]|(?!\1)[^\r\n\\])*\1?/g},strDouble:{type:"str",match:/"((?!")[^\r\n\\]|\\[^])*"?/g}};var $e=d({"./languages/asm.js":()=>Promise.resolve().then(()=>(G(),B)),"./languages/bash.js":()=>Promise.resolve().then(()=>(N(),H)),"./languages/bf.js":()=>Promise.resolve().then(()=>(_(),z)),"./languages/c.js":()=>Promise.resolve().then(()=>(Z(),Y)),"./languages/css.js":()=>Promise.resolve().then(()=>(W(),X)),"./languages/csv.js":()=>Promise.resolve().then(()=>(K(),j)),"./languages/diff.js":()=>Promise.resolve().then(()=>(R(),V)),"./languages/docker.js":()=>Promise.resolve().then(()=>(Q(),q)),"./languages/git.js":()=>Promise.resolve().then(()=>(tt(),J)),"./languages/go.js":()=>Promise.resolve().then(()=>(at(),et)),"./languages/html.js":()=>Promise.resolve().then(()=>(rt(),st)),"./languages/http.js":()=>Promise.resolve().then(()=>(mt(),ct)),"./languages/ini.js":()=>Promise.resolve().then(()=>(lt(),ot)),"./languages/java.js":()=>Promise.resolve().then(()=>(Et(),ut)),"./languages/js.js":()=>Promise.resolve().then(()=>(S(),it)),"./languages/js_template_literals.js":()=>Promise.resolve().then(()=>(gt(),ht)),"./languages/jsdoc.js":()=>Promise.resolve().then(()=>(yt(),bt)),"./languages/json.js":()=>Promise.resolve().then(()=>(ft(),Tt)),"./languages/leanpub-md.js":()=>Promise.resolve().then(()=>(At(),Nt)),"./languages/log.js":()=>Promise.resolve().then(()=>(Ot(),Rt)),"./languages/lua.js":()=>Promise.resolve().then(()=>(Lt(),xt)),"./languages/make.js":()=>Promise.resolve().then(()=>(Ct(),St)),"./languages/md.js":()=>Promise.resolve().then(()=>(U(),It)),"./languages/pl.js":()=>Promise.resolve().then(()=>(wt(),Dt)),"./languages/plain.js":()=>Promise.resolve().then(()=>(Pt(),Ut)),"./languages/py.js":()=>Promise.resolve().then(()=>(Mt(),Ft)),"./languages/regex.js":()=>Promise.resolve().then(()=>(vt(),$t)),"./languages/rs.js":()=>Promise.resolve().then(()=>(Gt(),Bt)),"./languages/sql.js":()=>Promise.resolve().then(()=>(Ht(),kt)),"./languages/todo.js":()=>Promise.resolve().then(()=>(D(),dt)),"./languages/toml.js":()=>Promise.resolve().then(()=>(_t(),zt)),"./languages/ts.js":()=>Promise.resolve().then(()=>(Zt(),Yt)),"./languages/uri.js":()=>Promise.resolve().then(()=>(Wt(),Xt)),"./languages/xml.js":()=>Promise.resolve().then(()=>(x(),pt)),"./languages/yaml.js":()=>Promise.resolve().then(()=>(Kt(),jt))});var P={};async function F(n,t,s){try{let r,m,c={},T,o=[],h=0,f=typeof t=="string"?await(P[t]??(P[t]=$e(`./languages/${t}.js`))):t,g=[...typeof t=="string"?f.default:t.sub];for(;h<n.length;){for(c.index=null,r=g.length;r-- >0;){if(m=g[r].expand?v[g[r].expand]:g[r],o[r]===void 0||o[r].match.index<h){if(m.match.lastIndex=h,T=m.match.exec(n),T===null){g.splice(r,1),o.splice(r,1);continue}o[r]={match:T,lastIndex:m.match.lastIndex}}o[r].match[0]&&(o[r].match.index<=c.index||c.index===null)&&(c={part:m,index:o[r].match.index,match:o[r].match[0],end:o[r].lastIndex})}if(c.index===null)break;s(n.slice(h,c.index),f.type),h=c.end,c.part.sub?await F(c.match,typeof c.part.sub=="string"?c.part.sub:typeof c.part.sub=="function"?c.part.sub(c.match):c.part,s):s(c.match,c.part.type)}s(n.slice(h,n.length),f.type)}catch{s(n)}}var Ge=d({"./themes/atom-dark.js":()=>Promise.resolve().then(()=>(Qt(),qt)),"./themes/default.js":()=>Promise.resolve().then(()=>($(),M)),"./themes/termcolor.js":()=>Promise.resolve().then(()=>(y(),Vt))});var Jt=Promise.resolve().then(()=>($(),M)),ke=async(n,t)=>{let s="",r=(await Jt).default;return await F(n,t,(m,c)=>s+=c?`${r[c]??""}${m}\x1B[0m`:m),s},la=async(n,t)=>console.log(await ke(n,t)),ua=async n=>Jt=Ge(`./themes/${n}.js`);export{ke as highlightText,la as printHighlight,ua as setTheme}; |
| { | ||
| "name": "@speed-highlight/core", | ||
| "version": "1.2.12", | ||
| "version": "1.2.14", | ||
| "description": "🌈 Light, fast, and easy to use, dependencies free javascript syntax highlighter, with automatic language detection", | ||
@@ -62,3 +62,3 @@ "main": "./dist/index.js", | ||
| "lightningcss-cli": "^1.25.1", | ||
| "semantic-release": "^24.0.0", | ||
| "semantic-release": "^25.0.2", | ||
| "typescript": "^5.3.3" | ||
@@ -65,0 +65,0 @@ }, |
@@ -40,8 +40,8 @@ //#region src/utils.ts | ||
| } | ||
| function serialTaskCaller(hooks, args) { | ||
| if (hooks.length > 0) return callHooks(hooks, args, 0, createTask(args.shift())); | ||
| function serialTaskCaller(hooks, args, name) { | ||
| if (hooks.length > 0) return callHooks(hooks, args, 0, createTask(name)); | ||
| } | ||
| function parallelTaskCaller(hooks, args) { | ||
| function parallelTaskCaller(hooks, args, name) { | ||
| if (hooks.length > 0) { | ||
| const task = createTask(args.shift()); | ||
| const task = createTask(name); | ||
| return Promise.all(hooks.map((hook) => task.run(() => hook(...args)))); | ||
@@ -168,4 +168,3 @@ } | ||
| if (this._before) callEachWith(this._before, event); | ||
| const _args = args?.length ? [name, ...args] : [name]; | ||
| const result = caller(this._hooks[name] ? [...this._hooks[name]] : [], _args); | ||
| const result = caller(this._hooks[name] ? [...this._hooks[name]] : [], args, name); | ||
| if (result instanceof Promise) return result.finally(() => { | ||
@@ -172,0 +171,0 @@ if (this._after && event) callEachWith(this._after, event); |
| { | ||
| "name": "hookable", | ||
| "version": "6.0.0-rc.1", | ||
| "version": "6.0.1", | ||
| "description": "Awaitable hook system", | ||
@@ -31,3 +31,3 @@ "keywords": [ | ||
| "prepublish": "pnpm build", | ||
| "release": "pnpm test && pnpm build && changelogen --release --prerelease --publish --publishTag rc --push", | ||
| "release": "pnpm test && pnpm build && changelogen --release --publish --push", | ||
| "test": "pnpm lint && vitest run --coverage", | ||
@@ -37,18 +37,18 @@ "test:types": "tsc --noEmit" | ||
| "devDependencies": { | ||
| "@types/node": "^24.9.1", | ||
| "@vitest/coverage-v8": "^4.0.3", | ||
| "@types/node": "^25.0.3", | ||
| "@vitest/coverage-v8": "^4.0.16", | ||
| "changelogen": "^0.6.2", | ||
| "esbuild": "^0.25.11", | ||
| "eslint": "^9.38.0", | ||
| "esbuild": "^0.27.2", | ||
| "eslint": "^9.39.2", | ||
| "eslint-config-unjs": "^0.5.0", | ||
| "expect-type": "^1.2.2", | ||
| "hookable-prev": "npm:hookable@^5.0.0", | ||
| "expect-type": "^1.3.0", | ||
| "hookable-prev": "npm:hookable@^5.5.3", | ||
| "mitata": "^1.0.34", | ||
| "obuild": "^0.3.0", | ||
| "prettier": "^3.6.2", | ||
| "obuild": "^0.4.9", | ||
| "prettier": "^3.7.4", | ||
| "typescript": "^5.9.3", | ||
| "vite": "^7.1.12", | ||
| "vitest": "^4.0.3" | ||
| "vite": "^7.3.0", | ||
| "vitest": "^4.0.16" | ||
| }, | ||
| "packageManager": "pnpm@10.19.0" | ||
| "packageManager": "pnpm@10.26.0" | ||
| } |
@@ -24,7 +24,7 @@ const n = /[^\0-\x7E]/; | ||
| function toASCII(o2) { | ||
| return function(n2, o3) { | ||
| return (function(n2, o3) { | ||
| const e2 = n2.split("@"); | ||
| let r2 = ""; | ||
| e2.length > 1 && (r2 = e2[0] + "@", n2 = e2[1]); | ||
| const s2 = function(n3, t2) { | ||
| const s2 = (function(n3, t2) { | ||
| const o4 = []; | ||
@@ -36,8 +36,8 @@ let e3 = n3.length; | ||
| return o4; | ||
| }((n2 = n2.replace(t, ".")).split("."), o3).join("."); | ||
| })((n2 = n2.replace(t, ".")).split("."), o3).join("."); | ||
| return r2 + s2; | ||
| }(o2, function(t2) { | ||
| return n.test(t2) ? "xn--" + function(n2) { | ||
| })(o2, function(t2) { | ||
| return n.test(t2) ? "xn--" + (function(n2) { | ||
| const t3 = []; | ||
| const o3 = (n2 = function(n3) { | ||
| const o3 = (n2 = (function(n3) { | ||
| const t4 = []; | ||
@@ -56,3 +56,3 @@ let o4 = 0; | ||
| return t4; | ||
| }(n2)).length; | ||
| })(n2)).length; | ||
| let f = 128; | ||
@@ -91,3 +91,3 @@ let i = 0; | ||
| return t3.join(""); | ||
| }(t2) : t2; | ||
| })(t2) : t2; | ||
| }); | ||
@@ -274,3 +274,6 @@ } | ||
| if (input.startsWith(_base)) { | ||
| return input; | ||
| const nextChar = input[_base.length]; | ||
| if (!nextChar || nextChar === "/" || nextChar === "?") { | ||
| return input; | ||
| } | ||
| } | ||
@@ -287,2 +290,6 @@ return joinURL(_base, input); | ||
| } | ||
| const nextChar = input[_base.length]; | ||
| if (nextChar && nextChar !== "/" && nextChar !== "?") { | ||
| return input; | ||
| } | ||
| const trimmed = input.slice(_base.length); | ||
@@ -289,0 +296,0 @@ return trimmed[0] === "/" ? trimmed : "/" + trimmed; |
| { | ||
| "name": "ufo", | ||
| "version": "1.6.1", | ||
| "version": "1.6.3", | ||
| "description": "URL utils for humans", | ||
@@ -11,4 +11,5 @@ "repository": "unjs/ufo", | ||
| "types": "./dist/index.d.ts", | ||
| "import": "./dist/index.mjs", | ||
| "require": "./dist/index.cjs", | ||
| "import": "./dist/index.mjs" | ||
| "default": "./dist/index.mjs" | ||
| }, | ||
@@ -34,16 +35,16 @@ "./*": "./*" | ||
| "devDependencies": { | ||
| "@types/node": "^22.14.0", | ||
| "@vitest/coverage-v8": "^3.1.1", | ||
| "automd": "^0.4.0", | ||
| "changelogen": "^0.6.1", | ||
| "eslint": "^9.24.0", | ||
| "eslint-config-unjs": "^0.4.2", | ||
| "jiti": "^2.4.2", | ||
| "prettier": "^3.5.3", | ||
| "typescript": "^5.8.3", | ||
| "unbuild": "^3.5.0", | ||
| "@types/node": "^25.0.8", | ||
| "@vitest/coverage-v8": "^4.0.17", | ||
| "automd": "^0.4.2", | ||
| "changelogen": "^0.6.2", | ||
| "eslint": "^9.39.2", | ||
| "eslint-config-unjs": "^0.6.2", | ||
| "jiti": "^2.6.1", | ||
| "prettier": "^3.7.4", | ||
| "typescript": "^5.9.3", | ||
| "unbuild": "^3.6.1", | ||
| "untyped": "^2.0.0", | ||
| "vitest": "^3.1.1" | ||
| "vitest": "^4.0.17" | ||
| }, | ||
| "packageManager": "pnpm@10.7.1" | ||
| "packageManager": "pnpm@10.28.0" | ||
| } |
| { | ||
| "name": "unctx", | ||
| "version": "2.4.1", | ||
| "version": "2.5.0", | ||
| "description": "Composition-api in Vanilla js", | ||
@@ -48,21 +48,21 @@ "repository": "unjs/unctx", | ||
| "dependencies": { | ||
| "acorn": "^8.14.0", | ||
| "acorn": "^8.15.0", | ||
| "estree-walker": "^3.0.3", | ||
| "magic-string": "^0.30.17", | ||
| "unplugin": "^2.1.0" | ||
| "magic-string": "^0.30.21", | ||
| "unplugin": "^2.3.11" | ||
| }, | ||
| "devDependencies": { | ||
| "@types/estree": "^1.0.6", | ||
| "@types/node": "^22.10.2", | ||
| "@vitest/coverage-v8": "^2.1.8", | ||
| "changelogen": "^0.5.7", | ||
| "eslint": "^9.17.0", | ||
| "eslint-config-unjs": "^0.4.2", | ||
| "jiti": "^2.4.2", | ||
| "prettier": "^3.4.2", | ||
| "typescript": "^5.7.2", | ||
| "unbuild": "^3.0.1", | ||
| "vitest": "^2.1.8" | ||
| "@types/estree": "^1.0.8", | ||
| "@types/node": "^25.0.2", | ||
| "@vitest/coverage-v8": "^4.0.16", | ||
| "changelogen": "^0.6.2", | ||
| "eslint": "^9.39.2", | ||
| "eslint-config-unjs": "^0.5.0", | ||
| "jiti": "^2.6.1", | ||
| "prettier": "^3.7.4", | ||
| "typescript": "^5.9.3", | ||
| "unbuild": "^3.6.1", | ||
| "vitest": "^4.0.16" | ||
| }, | ||
| "packageManager": "pnpm@9.15.0" | ||
| "packageManager": "pnpm@10.26.0" | ||
| } |
| import { | ||
| Layout | ||
| } from "./chunk-F4I6KX4R.js"; | ||
| } from "./chunk-CM7DWJNZ.js"; | ||
| import { | ||
| ErrorCause | ||
| } from "./chunk-PINJDICN.js"; | ||
| } from "./chunk-X53OIOJH.js"; | ||
| import { | ||
| ErrorInfo | ||
| } from "./chunk-EUJBVOYB.js"; | ||
| } from "./chunk-OIJ3WD7L.js"; | ||
| import { | ||
| ErrorMetadata | ||
| } from "./chunk-HFSXRSKS.js"; | ||
| } from "./chunk-P36L72PL.js"; | ||
| import { | ||
| ErrorStack | ||
| } from "./chunk-YYEJ3AGB.js"; | ||
| } from "./chunk-EJH674NB.js"; | ||
| import { | ||
| ErrorStackSource | ||
| } from "./chunk-4XB2BYKC.js"; | ||
| } from "./chunk-7QV3D5YX.js"; | ||
| import "./chunk-4L7RY2JA.js"; | ||
| import { | ||
| Header | ||
| } from "./chunk-PUHGL6HA.js"; | ||
| import "./chunk-OSUFJZHZ.js"; | ||
| } from "./chunk-AUGPHE32.js"; | ||
| import { | ||
| BaseComponent | ||
| } from "./chunk-4YEN7HVQ.js"; | ||
| } from "./chunk-PE3GG3TN.js"; | ||
@@ -28,0 +27,0 @@ // src/youch.ts |
@@ -41,2 +41,3 @@ :root { | ||
| position: relative; | ||
| word-break: break-word; | ||
| } | ||
@@ -43,0 +44,0 @@ #error-message svg { |
@@ -78,2 +78,3 @@ :root { | ||
| max-width: 100%; | ||
| word-wrap: break-word; | ||
| } | ||
@@ -97,5 +98,3 @@ | ||
| text-decoration: none; | ||
| white-space: nowrap; | ||
| overflow: hidden; | ||
| text-overflow: ellipsis; | ||
| text-align: left; | ||
| } | ||
@@ -102,0 +101,0 @@ .stack-frame-location span { |
| { | ||
| "name": "youch", | ||
| "description": "Pretty print JavaScript errors on the Web and the Terminal", | ||
| "version": "4.1.0-beta.12", | ||
| "version": "4.1.0-beta.13", | ||
| "type": "module", | ||
@@ -6,0 +6,0 @@ "files": [ |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| export {}; |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { Server } from "node:http"; | ||
@@ -8,6 +8,5 @@ import { parentPort, threadId } from "node:worker_threads"; | ||
| import { useNitroApp, useNitroHooks } from "nitro/app"; | ||
| import { startScheduleRunner } from "nitro/~internal/runtime/task"; | ||
| import { trapUnhandledErrors } from "nitro/~internal/runtime/error/hooks"; | ||
| import { resolveWebsocketHooks } from "nitro/~internal/runtime/app"; | ||
| import { hasWebSocket } from "#nitro-internal-virtual/feature-flags"; | ||
| import { startScheduleRunner } from "#nitro/runtime/task"; | ||
| import { trapUnhandledErrors } from "#nitro/runtime/error/hooks"; | ||
| import { resolveWebsocketHooks } from "#nitro/runtime/app"; | ||
| // Listen for shutdown signal from runner | ||
@@ -29,3 +28,3 @@ parentPort?.on("message", (msg) => { | ||
| // https://crossws.unjs.io/adapters/node | ||
| if (hasWebSocket) { | ||
| if (import.meta._websocket) { | ||
| const { handleUpgrade } = wsAdapter({ resolve: resolveWebsocketHooks }); | ||
@@ -32,0 +31,0 @@ server.on("upgrade", handleUpgrade); |
@@ -1,3 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| declare const _default: {}; | ||
| export default _default; |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import consola from "consola"; | ||
@@ -3,0 +3,0 @@ import { useNitroApp, useNitroHooks } from "nitro/app"; |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| export {}; |
@@ -1,4 +0,4 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import { isPublicAssetURL } from "#nitro-internal-virtual/public-assets"; | ||
| import { isPublicAssetURL } from "#nitro/virtual/public-assets"; | ||
| const nitroApp = useNitroApp(); | ||
@@ -5,0 +5,0 @@ // @ts-expect-error |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| export {}; |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { useNitroApp } from "nitro/app"; | ||
@@ -3,0 +3,0 @@ import { Server } from "node:http"; |
| import type { APIGatewayProxyEvent, APIGatewayProxyEventV2 } from "aws-lambda"; | ||
| import type { ServerRequest } from "srvx"; | ||
| // Incoming (AWS => Web) | ||
| export declare function awsRequest(event: APIGatewayProxyEvent | APIGatewayProxyEventV2, context: unknown): ServerRequest; | ||
| // Outgoing (Web => AWS) | ||
| export declare function awsResponseHeaders(response: Response); | ||
| // AWS Lambda proxy integrations requires base64 encoded buffers | ||
| // binaryMediaTypes should be */* | ||
| // see https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html | ||
| export declare function awsResponseBody(response: Response): Promise<{ | ||
@@ -11,0 +6,0 @@ body: string; |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| export declare const handler: unknown; |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { useNitroApp } from "nitro/app"; | ||
@@ -13,12 +13,10 @@ import { awsRequest, awsResponseHeaders } from "./_utils.mjs"; | ||
| }; | ||
| if (response.body) { | ||
| const writer = awslambda.HttpResponseStream.from( | ||
| // @ts-expect-error TODO: IMPORTANT! It should be a Writable according to the aws-lambda types | ||
| responseStream, | ||
| httpResponseMetadata | ||
| ); | ||
| const reader = response.body.getReader(); | ||
| await streamToNodeStream(reader, responseStream); | ||
| writer.end(); | ||
| } | ||
| const body = response.body ?? new ReadableStream({ start(controller) { | ||
| controller.enqueue(""); | ||
| controller.close(); | ||
| } }); | ||
| const writer = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata); | ||
| const reader = body.getReader(); | ||
| await streamToNodeStream(reader, responseStream); | ||
| writer.end(); | ||
| }); | ||
@@ -25,0 +23,0 @@ async function streamToNodeStream(reader, writer) { |
@@ -1,3 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import type { APIGatewayProxyEvent, APIGatewayProxyEventV2, APIGatewayProxyResult, APIGatewayProxyResultV2, Context } from "aws-lambda"; | ||
| export declare function handler(event: APIGatewayProxyEvent | APIGatewayProxyEventV2, context: Context): Promise<APIGatewayProxyResult | APIGatewayProxyResultV2>; |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { useNitroApp } from "nitro/app"; | ||
@@ -3,0 +3,0 @@ import { awsRequest, awsResponseHeaders, awsResponseBody } from "./_utils.mjs"; |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import type { HttpRequest, HttpResponse } from "@azure/functions"; | ||
@@ -3,0 +3,0 @@ export declare function handle(context: { |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { parseURL } from "ufo"; | ||
@@ -3,0 +3,0 @@ import { useNitroApp } from "nitro/app"; |
@@ -1,3 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| declare const _default: {}; | ||
| export default _default; |
@@ -1,9 +0,8 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { serve } from "srvx/bun"; | ||
| import wsAdapter from "crossws/adapters/bun"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import { startScheduleRunner } from "nitro/~internal/runtime/task"; | ||
| import { trapUnhandledErrors } from "nitro/~internal/runtime/error/hooks"; | ||
| import { resolveWebsocketHooks } from "nitro/~internal/runtime/app"; | ||
| import { hasWebSocket } from "#nitro-internal-virtual/feature-flags"; | ||
| import { startScheduleRunner } from "#nitro/runtime/task"; | ||
| import { trapUnhandledErrors } from "#nitro/runtime/error/hooks"; | ||
| import { resolveWebsocketHooks } from "#nitro/runtime/app"; | ||
| const port = Number.parseInt(process.env.NITRO_PORT || process.env.PORT || "") || 3e3; | ||
@@ -16,4 +15,4 @@ const host = process.env.NITRO_HOST || process.env.HOST; | ||
| let _fetch = nitroApp.fetch; | ||
| const ws = hasWebSocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined; | ||
| if (hasWebSocket) { | ||
| const ws = import.meta._websocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined; | ||
| if (import.meta._websocket) { | ||
| _fetch = (req) => { | ||
@@ -34,3 +33,3 @@ if (req.headers.get("upgrade") === "websocket") { | ||
| fetch: _fetch, | ||
| bun: { websocket: hasWebSocket ? ws?.websocket : undefined } | ||
| bun: { websocket: import.meta._websocket ? ws?.websocket : undefined } | ||
| }); | ||
@@ -37,0 +36,0 @@ trapUnhandledErrors(); |
@@ -1,4 +0,4 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import type * as CF from "@cloudflare/workers-types"; | ||
| import type { ExportedHandler } from "@cloudflare/workers-types"; | ||
| import type { ServerRuntimeContext } from "srvx"; | ||
| type MaybePromise<T> = T | Promise<T>; | ||
@@ -15,3 +15,3 @@ export declare function createHandler<Env>(hooks: { | ||
| }; | ||
| export declare function fetchHandler(cfReq: Request | CF.Request, env: unknown, context: CF.ExecutionContext | DurableObjectState, url: URL, nitroApp, ctxExt: any); | ||
| export declare function augmentReq(cfReq: Request | CF.Request, ctx: NonNullable<ServerRuntimeContext["cloudflare"]>); | ||
| export {}; |
@@ -1,3 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import { runCronTasks } from "nitro/~internal/runtime/task"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { runCronTasks } from "#nitro/runtime/task"; | ||
| import { useNitroApp, useNitroHooks } from "nitro/app"; | ||
@@ -9,2 +9,7 @@ export function createHandler(hooks) { | ||
| async fetch(request, env, context) { | ||
| globalThis.__env__ = env; | ||
| augmentReq(request, { | ||
| env, | ||
| context | ||
| }); | ||
| const ctxExt = {}; | ||
@@ -19,3 +24,3 @@ const url = new URL(request.url); | ||
| } | ||
| return fetchHandler(request, env, context, url, nitroApp, ctxExt); | ||
| return await nitroApp.fetch(request); | ||
| }, | ||
@@ -28,3 +33,3 @@ scheduled(controller, env, context) { | ||
| context | ||
| })); | ||
| }) || Promise.resolve()); | ||
| if (import.meta._tasks) { | ||
@@ -47,3 +52,3 @@ context.waitUntil(runCronTasks(controller.cron, { | ||
| context | ||
| })); | ||
| }) || Promise.resolve()); | ||
| }, | ||
@@ -57,3 +62,3 @@ queue(batch, env, context) { | ||
| context | ||
| })); | ||
| }) || Promise.resolve()); | ||
| }, | ||
@@ -66,3 +71,3 @@ tail(traces, env, context) { | ||
| context | ||
| })); | ||
| }) || Promise.resolve()); | ||
| }, | ||
@@ -75,18 +80,15 @@ trace(traces, env, context) { | ||
| context | ||
| })); | ||
| }) || Promise.resolve()); | ||
| } | ||
| }; | ||
| } | ||
| export async function fetchHandler(cfReq, env, context, url = new URL(cfReq.url), nitroApp = useNitroApp(), ctxExt) { | ||
| // Expose latest env to the global context | ||
| globalThis.__env__ = env; | ||
| // srvx compatibility | ||
| export function augmentReq(cfReq, ctx) { | ||
| const req = cfReq; | ||
| req.ip = cfReq.headers.get("cf-connecting-ip") || undefined; | ||
| req.runtime ??= { name: "cloudflare" }; | ||
| req.runtime.cloudflare ??= { | ||
| context, | ||
| env | ||
| req.runtime.cloudflare = { | ||
| ...req.runtime.cloudflare, | ||
| ...ctx | ||
| }; | ||
| req.waitUntil = context.waitUntil.bind(context); | ||
| return nitroApp.fetch(req); | ||
| req.waitUntil = ctx.context?.waitUntil.bind(ctx.context); | ||
| } |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { DurableObject } from "cloudflare:workers"; | ||
@@ -3,0 +3,0 @@ declare const _default; |
@@ -1,9 +0,8 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { DurableObject } from "cloudflare:workers"; | ||
| import wsAdapter from "crossws/adapters/cloudflare"; | ||
| import { createHandler, fetchHandler } from "./_module-handler.mjs"; | ||
| import { createHandler, augmentReq } from "./_module-handler.mjs"; | ||
| import { useNitroApp, useNitroHooks } from "nitro/app"; | ||
| import { isPublicAssetURL } from "#nitro-internal-virtual/public-assets"; | ||
| import { resolveWebsocketHooks } from "nitro/~internal/runtime/app"; | ||
| import { hasWebSocket } from "#nitro-internal-virtual/feature-flags"; | ||
| import { isPublicAssetURL } from "#nitro/virtual/public-assets"; | ||
| import { resolveWebsocketHooks } from "#nitro/runtime/app"; | ||
| const DURABLE_BINDING = "$DurableObject"; | ||
@@ -21,3 +20,3 @@ const DURABLE_INSTANCE = "server"; | ||
| }; | ||
| const ws = hasWebSocket ? wsAdapter({ | ||
| const ws = import.meta._websocket ? wsAdapter({ | ||
| resolve: resolveWebsocketHooks, | ||
@@ -36,3 +35,3 @@ instanceName: DURABLE_INSTANCE, | ||
| // https://crossws.unjs.io/adapters/cloudflare#durable-objects | ||
| if (hasWebSocket && request.headers.get("upgrade") === "websocket") { | ||
| if (import.meta._websocket && request.headers.get("upgrade") === "websocket") { | ||
| return ws.handleUpgrade(request, env, context); | ||
@@ -47,4 +46,4 @@ } | ||
| env | ||
| })); | ||
| if (hasWebSocket) { | ||
| }) || Promise.resolve()); | ||
| if (import.meta._websocket) { | ||
| ws.handleDurableInit(this, state, env); | ||
@@ -54,14 +53,16 @@ } | ||
| fetch(request) { | ||
| if (hasWebSocket && request.headers.get("upgrade") === "websocket") { | ||
| augmentReq(request, { | ||
| env: this.env, | ||
| context: this.ctx | ||
| }); | ||
| if (import.meta._websocket && request.headers.get("upgrade") === "websocket") { | ||
| return ws.handleDurableUpgrade(this, request); | ||
| } | ||
| // Main handler | ||
| const url = new URL(request.url); | ||
| return fetchHandler(request, this.env, this.ctx, url, nitroApp, { durable: this }); | ||
| return nitroApp.fetch(request); | ||
| } | ||
| alarm() { | ||
| this.ctx.waitUntil(nitroHooks.callHook("cloudflare:durable:alarm", this)); | ||
| this.ctx.waitUntil(nitroHooks.callHook("cloudflare:durable:alarm", this) || Promise.resolve()); | ||
| } | ||
| async webSocketMessage(client, message) { | ||
| if (hasWebSocket) { | ||
| if (import.meta._websocket) { | ||
| return ws.handleDurableMessage(this, client, message); | ||
@@ -71,3 +72,3 @@ } | ||
| async webSocketClose(client, code, reason, wasClean) { | ||
| if (hasWebSocket) { | ||
| if (import.meta._websocket) { | ||
| return ws.handleDurableClose(this, client, code, reason, wasClean); | ||
@@ -74,0 +75,0 @@ } |
@@ -1,3 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| declare const _default; | ||
| export default _default; |
@@ -1,18 +0,17 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import wsAdapter from "crossws/adapters/cloudflare"; | ||
| import { isPublicAssetURL } from "#nitro-internal-virtual/public-assets"; | ||
| import { isPublicAssetURL } from "#nitro/virtual/public-assets"; | ||
| import { createHandler } from "./_module-handler.mjs"; | ||
| import { resolveWebsocketHooks } from "nitro/~internal/runtime/app"; | ||
| import { hasWebSocket } from "#nitro-internal-virtual/feature-flags"; | ||
| const ws = hasWebSocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined; | ||
| export default createHandler({ fetch(request, env, context, url) { | ||
| import { resolveWebsocketHooks } from "#nitro/runtime/app"; | ||
| const ws = import.meta._websocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined; | ||
| export default createHandler({ fetch(cfRequest, env, context, url) { | ||
| // Static assets fallback (optional binding) | ||
| if (env.ASSETS && isPublicAssetURL(url.pathname)) { | ||
| return env.ASSETS.fetch(request); | ||
| return env.ASSETS.fetch(cfRequest); | ||
| } | ||
| // Websocket upgrade | ||
| // https://crossws.unjs.io/adapters/cloudflare | ||
| if (hasWebSocket && request.headers.get("upgrade") === "websocket") { | ||
| return ws.handleUpgrade(request, env, context); | ||
| if (import.meta._websocket && cfRequest.headers.get("upgrade") === "websocket") { | ||
| return ws.handleUpgrade(cfRequest, env, context); | ||
| } | ||
| } }); |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import type { Request as CFRequest, EventContext, ExecutionContext } from "@cloudflare/workers-types"; | ||
@@ -3,0 +3,0 @@ /** |
@@ -1,23 +0,19 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import wsAdapter from "crossws/adapters/cloudflare"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import { isPublicAssetURL } from "#nitro-internal-virtual/public-assets"; | ||
| import { runCronTasks } from "nitro/~internal/runtime/task"; | ||
| import { resolveWebsocketHooks } from "nitro/~internal/runtime/app"; | ||
| import { hasWebSocket } from "#nitro-internal-virtual/feature-flags"; | ||
| import { isPublicAssetURL } from "#nitro/virtual/public-assets"; | ||
| import { runCronTasks } from "#nitro/runtime/task"; | ||
| import { resolveWebsocketHooks } from "#nitro/runtime/app"; | ||
| import { augmentReq } from "./_module-handler.mjs"; | ||
| const nitroApp = useNitroApp(); | ||
| const ws = hasWebSocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined; | ||
| const ws = import.meta._websocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined; | ||
| export default { | ||
| async fetch(cfReq, env, context) { | ||
| // srvx compatibility | ||
| const req = cfReq; | ||
| req.runtime ??= { name: "cloudflare" }; | ||
| req.runtime.cloudflare ??= { | ||
| context, | ||
| env | ||
| }; | ||
| req.waitUntil = context.waitUntil.bind(context); | ||
| augmentReq(cfReq, { | ||
| env, | ||
| context | ||
| }); | ||
| // Websocket upgrade | ||
| // https://crossws.unjs.io/adapters/cloudflare | ||
| if (hasWebSocket && cfReq.headers.get("upgrade") === "websocket") { | ||
| if (import.meta._websocket && cfReq.headers.get("upgrade") === "websocket") { | ||
| return ws.handleUpgrade(cfReq, env, context); | ||
@@ -29,5 +25,3 @@ } | ||
| } | ||
| // Expose latest env to the global context | ||
| globalThis.__env__ = env; | ||
| return nitroApp.fetch(req); | ||
| return nitroApp.fetch(cfReq); | ||
| }, | ||
@@ -34,0 +28,0 @@ scheduled(event, env, context) { |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import type { Deno as _Deno } from "@deno/types"; | ||
@@ -3,0 +3,0 @@ declare global { |
@@ -1,8 +0,7 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import wsAdapter from "crossws/adapters/deno"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import { resolveWebsocketHooks } from "nitro/~internal/runtime/app"; | ||
| import { hasWebSocket } from "#nitro-internal-virtual/feature-flags"; | ||
| import { resolveWebsocketHooks } from "#nitro/runtime/app"; | ||
| const nitroApp = useNitroApp(); | ||
| const ws = hasWebSocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined; | ||
| const ws = import.meta._websocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined; | ||
| // TODO: Migrate to srvx to provide request IP | ||
@@ -16,3 +15,3 @@ Deno.serve((denoReq, info) => { | ||
| // https://crossws.unjs.io/adapters/deno | ||
| if (hasWebSocket && req.headers.get("upgrade") === "websocket") { | ||
| if (import.meta._websocket && req.headers.get("upgrade") === "websocket") { | ||
| return ws.handleUpgrade(req, info); | ||
@@ -19,0 +18,0 @@ } |
@@ -1,3 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| declare const _default: {}; | ||
| export default _default; |
@@ -1,9 +0,8 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { serve } from "srvx/deno"; | ||
| import wsAdapter from "crossws/adapters/deno"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import { startScheduleRunner } from "nitro/~internal/runtime/task"; | ||
| import { trapUnhandledErrors } from "nitro/~internal/runtime/error/hooks"; | ||
| import { resolveWebsocketHooks } from "nitro/~internal/runtime/app"; | ||
| import { hasWebSocket } from "#nitro-internal-virtual/feature-flags"; | ||
| import { startScheduleRunner } from "#nitro/runtime/task"; | ||
| import { trapUnhandledErrors } from "#nitro/runtime/error/hooks"; | ||
| import { resolveWebsocketHooks } from "#nitro/runtime/app"; | ||
| const port = Number.parseInt(process.env.NITRO_PORT || process.env.PORT || "") || 3e3; | ||
@@ -16,3 +15,3 @@ const host = process.env.NITRO_HOST || process.env.HOST; | ||
| let _fetch = nitroApp.fetch; | ||
| if (hasWebSocket) { | ||
| if (import.meta._websocket) { | ||
| const { handleUpgrade } = wsAdapter({ resolve: resolveWebsocketHooks }); | ||
@@ -19,0 +18,0 @@ _fetch = (req) => { |
@@ -1,4 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import type { Context } from "@netlify/edge-functions"; | ||
| // https://docs.netlify.com/edge-functions/api/ | ||
| export default function netlifyEdge(netlifyReq: Request, context: Context); |
@@ -1,4 +0,4 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import { isPublicAssetURL } from "#nitro-internal-virtual/public-assets"; | ||
| import { isPublicAssetURL } from "#nitro/virtual/public-assets"; | ||
| const nitroApp = useNitroApp(); | ||
@@ -9,2 +9,3 @@ // https://docs.netlify.com/edge-functions/api/ | ||
| const req = netlifyReq; | ||
| req.ip = context.ip; | ||
| req.runtime ??= { name: "netlify-edge" }; | ||
@@ -11,0 +12,0 @@ // @ts-expect-error (add to srvx types) |
@@ -1,3 +0,4 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| declare const handler: (req: Request) => Promise<Response>; | ||
| import "#nitro/virtual/polyfills"; | ||
| import type { ServerRequest } from "srvx"; | ||
| declare const handler: (req: ServerRequest) => Promise<Response>; | ||
| export default handler; |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { useNitroApp } from "nitro/app"; | ||
@@ -6,2 +6,4 @@ const nitroApp = useNitroApp(); | ||
| const handler = async (req) => { | ||
| req.runtime ??= { name: "netlify" }; | ||
| req.ip = req.headers.get("x-nf-client-connection-ip") || undefined; | ||
| const response = await nitroApp.fetch(req); | ||
@@ -8,0 +10,0 @@ const isr = (req.context?.routeRules || {})?.isr?.options; |
@@ -1,3 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| declare const _default: {}; | ||
| export default _default; |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import cluster from "node:cluster"; | ||
@@ -6,6 +6,5 @@ import { NodeRequest, serve } from "srvx/node"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import { startScheduleRunner } from "nitro/~internal/runtime/task"; | ||
| import { trapUnhandledErrors } from "nitro/~internal/runtime/error/hooks"; | ||
| import { resolveWebsocketHooks } from "nitro/~internal/runtime/app"; | ||
| import { hasWebSocket } from "#nitro-internal-virtual/feature-flags"; | ||
| import { startScheduleRunner } from "#nitro/runtime/task"; | ||
| import { trapUnhandledErrors } from "#nitro/runtime/error/hooks"; | ||
| import { resolveWebsocketHooks } from "#nitro/runtime/app"; | ||
| const port = Number.parseInt(process.env.NITRO_PORT || process.env.PORT || "") || 3e3; | ||
@@ -32,3 +31,3 @@ const host = process.env.NITRO_HOST || process.env.HOST; | ||
| }); | ||
| if (hasWebSocket) { | ||
| if (import.meta._websocket) { | ||
| const { handleUpgrade } = wsAdapter({ resolve: resolveWebsocketHooks }); | ||
@@ -35,0 +34,0 @@ server.node.server.on("upgrade", (req, socket, head) => { |
@@ -1,3 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| export declare const middleware: unknown; | ||
| export declare const handleUpgrade: unknown; |
@@ -1,11 +0,10 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { toNodeHandler } from "srvx/node"; | ||
| import wsAdapter from "crossws/adapters/node"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import { startScheduleRunner } from "nitro/~internal/runtime/task"; | ||
| import { resolveWebsocketHooks } from "nitro/~internal/runtime/app"; | ||
| import { hasWebSocket } from "#nitro-internal-virtual/feature-flags"; | ||
| import { startScheduleRunner } from "#nitro/runtime/task"; | ||
| import { resolveWebsocketHooks } from "#nitro/runtime/app"; | ||
| const nitroApp = useNitroApp(); | ||
| export const middleware = toNodeHandler(nitroApp.fetch); | ||
| const ws = hasWebSocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined; | ||
| const ws = import.meta._websocket ? wsAdapter({ resolve: resolveWebsocketHooks }) : undefined; | ||
| export const handleUpgrade = ws?.handleUpgrade; | ||
@@ -12,0 +11,0 @@ // Scheduled tasks |
@@ -1,3 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| declare const _default: {}; | ||
| export default _default; |
@@ -1,9 +0,8 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { NodeRequest, serve } from "srvx/node"; | ||
| import wsAdapter from "crossws/adapters/node"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import { startScheduleRunner } from "nitro/~internal/runtime/task"; | ||
| import { trapUnhandledErrors } from "nitro/~internal/runtime/error/hooks"; | ||
| import { resolveWebsocketHooks } from "nitro/~internal/runtime/app"; | ||
| import { hasWebSocket } from "#nitro-internal-virtual/feature-flags"; | ||
| import { startScheduleRunner } from "#nitro/runtime/task"; | ||
| import { trapUnhandledErrors } from "#nitro/runtime/error/hooks"; | ||
| import { resolveWebsocketHooks } from "#nitro/runtime/app"; | ||
| const port = Number.parseInt(process.env.NITRO_PORT || process.env.PORT || "") || 3e3; | ||
@@ -24,3 +23,3 @@ const host = process.env.NITRO_HOST || process.env.HOST; | ||
| }); | ||
| if (hasWebSocket) { | ||
| if (import.meta._websocket) { | ||
| const { handleUpgrade } = wsAdapter({ resolve: resolveWebsocketHooks }); | ||
@@ -27,0 +26,0 @@ server.node.server.on("upgrade", (req, socket, head) => { |
@@ -1,3 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| declare const _default: {}; | ||
| export default _default; |
@@ -1,4 +0,4 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| const nitroApp = useNitroApp(); | ||
| export default { fetch: nitroApp.fetch }; |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import type { Handler } from "aws-lambda"; | ||
@@ -3,0 +3,0 @@ type StormkitEvent = { |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { useNitroApp } from "nitro/app"; | ||
@@ -3,0 +3,0 @@ import { awsResponseBody } from "../../aws-lambda/runtime/_utils.mjs"; |
@@ -1,3 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import type { NodeServerRequest, NodeServerResponse } from "srvx"; | ||
| export default function nodeHandler(req: NodeServerRequest, res: NodeServerResponse); |
@@ -1,12 +0,21 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { toNodeHandler } from "srvx/node"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import { useNitroApp, getRouteRules } from "nitro/app"; | ||
| import { isrRouteRewrite } from "./isr.mjs"; | ||
| const nitroApp = useNitroApp(); | ||
| const handler = toNodeHandler(nitroApp.fetch); | ||
| export default function nodeHandler(req, res) { | ||
| const query = req.headers["x-now-route-matches"]; | ||
| if (query) { | ||
| const url = new URLSearchParams(query).get("url"); | ||
| if (url) { | ||
| req.url = decodeURIComponent(url); | ||
| // https://vercel.com/docs/headers/request-headers#x-forwarded-for | ||
| // srvx node adapter uses req.socket.remoteAddress for req.ip | ||
| let ip; | ||
| Object.defineProperty(req.socket, "remoteAddress", { get() { | ||
| const h = req.headers["x-forwarded-for"]; | ||
| return ip ??= h?.split?.(",").shift()?.trim(); | ||
| } }); | ||
| // ISR route rewrite | ||
| const isrURL = isrRouteRewrite(req.url, req.headers["x-now-route-matches"]); | ||
| if (isrURL) { | ||
| const { routeRules } = getRouteRules("", isrURL[0]); | ||
| if (routeRules?.isr) { | ||
| req.url = isrURL[0] + (isrURL[1] ? `?${isrURL[1]}` : ""); | ||
| } | ||
@@ -13,0 +22,0 @@ } |
@@ -1,2 +0,2 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import type { ServerRequest } from "srvx"; | ||
@@ -3,0 +3,0 @@ declare const _default: { |
@@ -1,20 +0,25 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { useNitroApp, getRouteRules } from "nitro/app"; | ||
| import { isrRouteRewrite } from "./isr.mjs"; | ||
| const nitroApp = useNitroApp(); | ||
| export default { fetch(req, context) { | ||
| // Check for ISR request | ||
| const query = req.headers.get("x-now-route-matches"); | ||
| if (query) { | ||
| const urlParam = new URLSearchParams(query).get("url"); | ||
| if (urlParam) { | ||
| const url = new URL(decodeURIComponent(urlParam), req.url).href; | ||
| req = new Request(url, req); | ||
| // ISR route rewrite | ||
| const isrURL = isrRouteRewrite(req.url, req.headers.get("x-now-route-matches")); | ||
| if (isrURL) { | ||
| const { routeRules } = getRouteRules("", isrURL[0]); | ||
| if (routeRules?.isr) { | ||
| req = new Request(new URL(isrURL[0] + (isrURL[1] ? `?${isrURL[1]}` : ""), req.url).href, req); | ||
| } | ||
| } | ||
| // srvx compatibility | ||
| req.runtime ??= { name: "vercel" }; | ||
| // @ts-expect-error (add to srvx types) | ||
| req.runtime.vercel = { context }; | ||
| req.runtime = { | ||
| name: "vercel", | ||
| vercel: { context } | ||
| }; | ||
| let ip; | ||
| Object.defineProperty(req, "ip", { get() { | ||
| const h = req.headers.get("x-forwarded-for"); | ||
| return ip ??= h?.split(",").shift()?.trim(); | ||
| } }); | ||
| req.waitUntil = context?.waitUntil; | ||
| return nitroApp.fetch(req); | ||
| } }; |
@@ -1,3 +0,2 @@ | ||
| // @ts-nocheck TODO: Remove after removing polyfills | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| export {}; |
| // @ts-nocheck TODO: Remove after removing polyfills | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { useNitroApp } from "nitro/app"; | ||
@@ -4,0 +4,0 @@ import { hasProtocol, joinURL } from "ufo"; |
@@ -1,3 +0,3 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| declare const _default; | ||
| export default _default; |
@@ -1,4 +0,4 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import { toNodeHandler } from "srvx/node"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| export default toNodeHandler(useNitroApp().fetch); |
@@ -1,1 +0,1 @@ | ||
| export { useNitroApp, useNitroHooks, serverFetch, fetch } from "./internal/app.mjs"; | ||
| export { useNitroApp, useNitroHooks, serverFetch, getRouteRules, fetch } from "./internal/app.mjs"; |
@@ -1,1 +0,1 @@ | ||
| export { useNitroApp, useNitroHooks, serverFetch, fetch } from "./internal/app.mjs"; | ||
| export { useNitroApp, useNitroHooks, serverFetch, getRouteRules, fetch } from "./internal/app.mjs"; |
@@ -1,7 +0,7 @@ | ||
| import type { NitroApp, NitroRuntimeHooks } from "nitro/types"; | ||
| import type { MatchedRouteRules, NitroApp, NitroRuntimeHooks } from "nitro/types"; | ||
| import type { ServerRequest, ServerRequestContext } from "srvx"; | ||
| import type { H3EventContext, WebSocketHooks } from "h3"; | ||
| import type { H3EventContext, Middleware, WebSocketHooks } from "h3"; | ||
| import { HookableCore } from "hookable"; | ||
| declare global { | ||
| var __nitro__: NitroApp | undefined; | ||
| var __nitro__: Partial<Record<"default" | "prerender" | (string & {}), NitroApp | undefined>> | undefined; | ||
| } | ||
@@ -13,1 +13,5 @@ export declare function useNitroApp(): NitroApp; | ||
| export declare function fetch(resource: string | URL | Request, init?: RequestInit, context?: ServerRequestContext | H3EventContext): Promise<Response>; | ||
| export declare function getRouteRules(method: string, pathname: string): { | ||
| routeRules?: MatchedRouteRules; | ||
| routeRuleMiddleware: Middleware[]; | ||
| }; |
@@ -5,8 +5,19 @@ import { H3Core, toRequest } from "h3"; | ||
| // IMPORTANT: virtual imports and user code should be imported last to avoid initialization order issues | ||
| import errorHandler from "#nitro-internal-virtual/error-handler"; | ||
| import { plugins } from "#nitro-internal-virtual/plugins"; | ||
| import { findRoute, findRouteRules, globalMiddleware, findRoutedMiddleware } from "#nitro-internal-virtual/routing"; | ||
| import { hasRouteRules, hasRoutedMiddleware, hasGlobalMiddleware, hasRoutes, hasHooks, hasPlugins } from "#nitro-internal-virtual/feature-flags"; | ||
| import errorHandler from "#nitro/virtual/error-handler"; | ||
| import { plugins } from "#nitro/virtual/plugins"; | ||
| import { findRoute, findRouteRules, globalMiddleware, findRoutedMiddleware } from "#nitro/virtual/routing"; | ||
| import { hasRouteRules, hasRoutedMiddleware, hasGlobalMiddleware, hasRoutes, hasHooks, hasPlugins } from "#nitro/virtual/feature-flags"; | ||
| const APP_ID = import.meta.prerender ? "prerender" : "default"; | ||
| export function useNitroApp() { | ||
| return useNitroApp.__instance__ ??= initNitroApp(); | ||
| let instance = useNitroApp._instance; | ||
| if (instance) { | ||
| return instance; | ||
| } | ||
| instance = useNitroApp._instance = createNitroApp(); | ||
| globalThis.__nitro__ = globalThis.__nitro__ || {}; | ||
| globalThis.__nitro__[APP_ID] = instance; | ||
| if (hasPlugins) { | ||
| initNitroPlugins(instance); | ||
| } | ||
| return instance; | ||
| } | ||
@@ -46,17 +57,2 @@ export function useNitroHooks() { | ||
| } | ||
| function initNitroApp() { | ||
| const nitroApp = createNitroApp(); | ||
| if (hasPlugins) { | ||
| for (const plugin of plugins) { | ||
| try { | ||
| plugin(nitroApp); | ||
| } catch (error) { | ||
| nitroApp.captureError?.(error, { tags: ["plugin"] }); | ||
| throw error; | ||
| } | ||
| } | ||
| } | ||
| globalThis.__nitro__ = nitroApp; | ||
| return nitroApp; | ||
| } | ||
| function createNitroApp() { | ||
@@ -76,3 +72,3 @@ const hooks = hasHooks ? new HookableCore() : undefined; | ||
| } | ||
| if (hasHooks && typeof errorCtx.event.req.waitUntil === "function") { | ||
| if (hasHooks && promise && typeof errorCtx.event.req.waitUntil === "function") { | ||
| errorCtx.event.req.waitUntil(promise); | ||
@@ -125,2 +121,13 @@ } | ||
| } | ||
| function initNitroPlugins(app) { | ||
| for (const plugin of plugins) { | ||
| try { | ||
| plugin(app); | ||
| } catch (error) { | ||
| app.captureError?.(error, { tags: ["plugin"] }); | ||
| throw error; | ||
| } | ||
| } | ||
| return app; | ||
| } | ||
| function createH3App(config) { | ||
@@ -155,3 +162,3 @@ // Create H3 app | ||
| } | ||
| function getRouteRules(method, pathname) { | ||
| export function getRouteRules(method, pathname) { | ||
| const m = findRouteRules(method, pathname); | ||
@@ -158,0 +165,0 @@ if (!m?.length) { |
| import { createDatabase } from "db0"; | ||
| import { connectionConfigs } from "#nitro-internal-virtual/database"; | ||
| import { connectionConfigs } from "#nitro/virtual/database"; | ||
| const instances = Object.create(null); | ||
@@ -4,0 +4,0 @@ export function useDatabase(name = "default") { |
@@ -9,3 +9,2 @@ import type { HTTPError, HTTPEvent } from "h3"; | ||
| }): Promise<InternalHandlerResponse>; | ||
| // ---- Source Map support ---- | ||
| export declare function loadStackTrace(error: any); |
@@ -47,3 +47,3 @@ import { getRequestURL } from "h3"; | ||
| // Use HTML response only when user-agent expects it (browsers) | ||
| const useJSON = opts?.json || !event.req.headers.get("accept")?.includes("text/html"); | ||
| const useJSON = opts?.json ?? !event.req.headers.get("accept")?.includes("text/html"); | ||
| // Prepare headers | ||
@@ -50,0 +50,0 @@ const headers = { |
@@ -1,8 +0,4 @@ | ||
| // Headers route rule | ||
| export declare const headers: unknown; | ||
| // Redirect route rule | ||
| export declare const redirect: unknown; | ||
| // Proxy route rule | ||
| export declare const proxy: unknown; | ||
| // Cache route rule | ||
| export declare const cache: unknown; |
| import { H3 } from "h3"; | ||
| import { runTask } from "../task.mjs"; | ||
| import { scheduledTasks, tasks } from "#nitro-internal-virtual/tasks"; | ||
| import { scheduledTasks, tasks } from "#nitro/virtual/tasks"; | ||
| export default new H3().get("/_nitro/tasks", async () => { | ||
@@ -5,0 +5,0 @@ const _tasks = await Promise.all(Object.entries(tasks).map(async ([name, task]) => { |
| import type { EventHandler } from "h3"; | ||
| // Served as /_openapi.json | ||
| declare const _default: EventHandler; | ||
| export default _default; |
| import { defineHandler, getRequestURL } from "h3"; | ||
| import { joinURL } from "ufo"; | ||
| import { defu } from "defu"; | ||
| import { handlersMeta } from "#nitro-internal-virtual/routing-meta"; | ||
| import { handlersMeta } from "#nitro/virtual/routing-meta"; | ||
| import { useRuntimeConfig } from "../runtime-config.mjs"; | ||
@@ -15,3 +15,3 @@ // Served as /_openapi.json | ||
| }; | ||
| const { paths, globals: { components,...globalsRest } } = getHandlersMeta(); | ||
| const { paths, globals: { components, ...globalsRest } } = getHandlersMeta(); | ||
| const extensible = Object.fromEntries(Object.entries(globalsRest).filter(([key]) => key.startsWith("x-"))); | ||
@@ -42,3 +42,3 @@ return { | ||
| const method = (h.method || "get").toLowerCase(); | ||
| const { $global,...openAPI } = h.meta?.openAPI || {}; | ||
| const { $global, ...openAPI } = h.meta?.openAPI || {}; | ||
| const item = { [method]: { | ||
@@ -45,0 +45,0 @@ tags, |
| import { serverFetch } from "../app.mjs"; | ||
| import { rendererTemplate, rendererTemplateFile, isStaticTemplate } from "#nitro-internal-virtual/renderer-template"; | ||
| import { rendererTemplate, rendererTemplateFile, isStaticTemplate } from "#nitro/virtual/renderer-template"; | ||
| import { HTTPResponse } from "h3"; | ||
@@ -4,0 +4,0 @@ import { hasTemplateSyntax, renderToResponse, compileTemplate } from "rendu"; |
@@ -1,4 +0,4 @@ | ||
| import { rendererTemplate } from "#nitro-internal-virtual/renderer-template"; | ||
| import { rendererTemplate } from "#nitro/virtual/renderer-template"; | ||
| export default function renderIndexHTML(event) { | ||
| return rendererTemplate(event.req); | ||
| } |
| import { type EventHandler } from "h3"; | ||
| // Served as /_scalar | ||
| declare const _default: EventHandler; | ||
| export default _default; |
@@ -6,7 +6,7 @@ import { defineHandler } from "h3"; | ||
| const runtimeConfig = useRuntimeConfig(); | ||
| const title = runtimeConfig.nitro.openAPI?.meta?.title || "API Reference"; | ||
| const description = runtimeConfig.nitro.openAPI?.meta?.description || ""; | ||
| const openAPIEndpoint = runtimeConfig.nitro.openAPI?.route || "./_openapi.json"; | ||
| const title = runtimeConfig.nitro?.openAPI?.meta?.title || "API Reference"; | ||
| const description = runtimeConfig.nitro?.openAPI?.meta?.description || ""; | ||
| const openAPIEndpoint = runtimeConfig.nitro?.openAPI?.route || "./_openapi.json"; | ||
| // https://github.com/scalar/scalar | ||
| const _config = runtimeConfig.nitro.openAPI?.ui?.scalar; | ||
| const _config = runtimeConfig.nitro?.openAPI?.ui?.scalar; | ||
| const scalarConfig = { | ||
@@ -13,0 +13,0 @@ ..._config, |
| import type { EventHandler } from "h3"; | ||
| // https://github.com/swagger-api/swagger-ui | ||
| declare const _default: EventHandler; | ||
| export default _default; |
@@ -6,5 +6,5 @@ import { defineHandler } from "h3"; | ||
| const runtimeConfig = useRuntimeConfig(); | ||
| const title = runtimeConfig.nitro.openAPI?.meta?.title || "API Reference"; | ||
| const description = runtimeConfig.nitro.openAPI?.meta?.description || ""; | ||
| const openAPIEndpoint = runtimeConfig.nitro.openAPI?.route || "./_openapi.json"; | ||
| const title = runtimeConfig.nitro?.openAPI?.meta?.title || "API Reference"; | ||
| const description = runtimeConfig.nitro?.openAPI?.meta?.description || ""; | ||
| const openAPIEndpoint = runtimeConfig.nitro?.openAPI?.route || "./_openapi.json"; | ||
| const CDN_BASE = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@^5"; | ||
@@ -11,0 +11,0 @@ event.res.headers.set("Content-Type", "text/html"); |
@@ -1,3 +0,3 @@ | ||
| import { runtimeConfig } from "#nitro-internal-virtual/runtime-config"; | ||
| import { snakeCase } from "scule"; | ||
| import { runtimeConfig } from "#nitro/virtual/runtime-config"; | ||
| export function useRuntimeConfig() { | ||
@@ -15,9 +15,2 @@ return useRuntimeConfig._cached ||= getRuntimeConfig(); | ||
| } | ||
| function getEnv(key, opts) { | ||
| const envKey = snakeCase(key).toUpperCase(); | ||
| return process.env[opts.prefix + envKey] ?? process.env[opts.altPrefix + envKey]; | ||
| } | ||
| function _isObject(input) { | ||
| return typeof input === "object" && !Array.isArray(input); | ||
| } | ||
| export function applyEnv(obj, opts, parentKey = "") { | ||
@@ -56,1 +49,8 @@ for (const key in obj) { | ||
| } | ||
| function getEnv(key, opts) { | ||
| const envKey = snakeCase(key).toUpperCase(); | ||
| return process.env[opts.prefix + envKey] ?? process.env[opts.altPrefix + envKey]; | ||
| } | ||
| function _isObject(input) { | ||
| return input !== null && typeof input === "object" && !Array.isArray(input); | ||
| } |
| import { HTTPError, defineHandler } from "h3"; | ||
| import { decodePath, joinURL, withLeadingSlash, withoutTrailingSlash } from "ufo"; | ||
| import { getAsset, isPublicAssetURL, readAsset } from "#nitro-internal-virtual/public-assets"; | ||
| import { getAsset, isPublicAssetURL, readAsset } from "#nitro/virtual/public-assets"; | ||
| const METHODS = new Set(["HEAD", "GET"]); | ||
@@ -5,0 +5,0 @@ const EncodingMap = { |
| import { prefixStorage } from "unstorage"; | ||
| import { initStorage } from "#nitro-internal-virtual/storage"; | ||
| import { initStorage } from "#nitro/virtual/storage"; | ||
| export function useStorage(base = "") { | ||
@@ -4,0 +4,0 @@ const storage = useStorage._storage ??= initStorage(); |
| import { Cron } from "croner"; | ||
| import { HTTPError } from "h3"; | ||
| import { scheduledTasks, tasks } from "#nitro-internal-virtual/tasks"; | ||
| import { scheduledTasks, tasks } from "#nitro/virtual/tasks"; | ||
| /** @experimental */ | ||
@@ -5,0 +5,0 @@ export function defineTask(def) { |
@@ -1,7 +0,6 @@ | ||
| import "#nitro-internal-pollyfills"; | ||
| import "#nitro/virtual/polyfills"; | ||
| import wsAdapter from "crossws/adapters/node"; | ||
| import { useNitroApp } from "nitro/app"; | ||
| import { resolveWebsocketHooks } from "nitro/~internal/runtime/app"; | ||
| import { hasWebSocket } from "#nitro-internal-virtual/feature-flags"; | ||
| import { resolveWebsocketHooks } from "#nitro/runtime/app"; | ||
@@ -12,3 +11,3 @@ const nitroApp = useNitroApp(); | ||
| const ws = hasWebSocket | ||
| const ws = import.meta._websocket | ||
| ? wsAdapter({ resolve: resolveWebsocketHooks }) | ||
@@ -15,0 +14,0 @@ : undefined; |
| export declare const version: string; | ||
| export declare const pkgDir: string; | ||
| export declare const runtimeDir: string; | ||
| export declare const presetsDir: string; | ||
| export declare const pkgDir: string; | ||
| export declare const runtimeDependencies: string[]; |
@@ -5,5 +5,5 @@ import { fileURLToPath } from "node:url"; | ||
| const resolve = (path) => fileURLToPath(new URL(path, import.meta.url)); | ||
| export const pkgDir = /* @__PURE__ */ resolve("../../"); | ||
| export const runtimeDir = /* @__PURE__ */ resolve("./"); | ||
| export const presetsDir = /* @__PURE__ */ resolve("../presets/"); | ||
| export const pkgDir = /* @__PURE__ */ resolve("../../"); | ||
| export const runtimeDependencies = [ | ||
@@ -10,0 +10,0 @@ "crossws", |
@@ -1,2 +0,1 @@ | ||
| // Config | ||
| import type { NitroConfig } from "nitro/types"; | ||
@@ -6,8 +5,6 @@ import type { ServerRequestContext } from "srvx"; | ||
| export declare function defineConfig(config: Omit<NitroConfig, "rootDir">): Omit<NitroConfig, "rootDir">; | ||
| // Type (only) helpers | ||
| export { defineNitroPlugin as definePlugin } from "./internal/plugin.mjs"; | ||
| export { defineRouteMeta } from "./internal/meta.mjs"; | ||
| export { defineNitroErrorHandler as defineErrorHandler } from "./internal/error/utils.mjs"; | ||
| // Runtime | ||
| export declare function serverFetch(resource: string | URL | Request, init?: RequestInit, context?: ServerRequestContext | H3EventContext): Promise<Response>; | ||
| export declare function fetch(resource: string | URL | Request, init?: RequestInit, context?: ServerRequestContext | H3EventContext): Promise<Response>; |
@@ -11,3 +11,3 @@ import { toRequest } from "h3"; | ||
| export function serverFetch(resource, init, context) { | ||
| const nitro = globalThis.__nitro__ || globalThis.__nitro_builder__; | ||
| const nitro = globalThis.__nitro__?.default || globalThis.__nitro__?.prerender || globalThis.__nitro_builder__; | ||
| if (!nitro) { | ||
@@ -14,0 +14,0 @@ return Promise.reject(new Error("Nitro instance is not available.")); |
+10
-0
@@ -0,1 +1,11 @@ | ||
| import "nitro"; | ||
| import "nitro/app"; | ||
| import "nitro/cache"; | ||
| import "nitro/context"; | ||
| import "nitro/database"; | ||
| import "nitro/h3"; | ||
| import "nitro/runtime-config"; | ||
| import "nitro/storage"; | ||
| import "nitro/task"; | ||
| export { }; |
+7
-12
@@ -0,5 +1,6 @@ | ||
| import "vite/client"; | ||
| import "nitro/vite/types"; | ||
| import "./_dev.mjs"; | ||
| import "unenv"; | ||
| import { Plugin } from "vite"; | ||
| import "rollup"; | ||
| import { Nitro, NitroConfig, NitroModule } from "nitro/types"; | ||
@@ -19,7 +20,2 @@ | ||
| } | ||
| declare module "rollup" { | ||
| interface Plugin { | ||
| nitro?: NitroModule; | ||
| } | ||
| } | ||
| interface NitroPluginConfig extends NitroConfig { | ||
@@ -33,7 +29,2 @@ /** | ||
| /** | ||
| * @experimental Use the virtual filesystem for intermediate environment build output files. | ||
| * @note This is unsafe if plugins rely on temporary files on the filesystem. | ||
| */ | ||
| virtualBundle?: boolean; | ||
| /** | ||
| * @experimental Enable `?assets` import proposed by https://github.com/vitejs/vite/discussions/20913 | ||
@@ -48,3 +39,7 @@ * @default true | ||
| */ | ||
| serverReload: boolean; | ||
| serverReload?: boolean; | ||
| /** | ||
| * Additional Vite environment services to register. | ||
| */ | ||
| services?: Record<string, ServiceConfig>; | ||
| }; | ||
@@ -51,0 +46,0 @@ }; |
+734
-41
@@ -1,44 +0,737 @@ | ||
| import "./_libs/c12.mjs"; | ||
| import "./_libs/gen-mapping.mjs"; | ||
| import "./_libs/magic-string.mjs"; | ||
| import "./_libs/acorn.mjs"; | ||
| import "./_libs/confbox.mjs"; | ||
| import "./_libs/local-pkg.mjs"; | ||
| import "./_libs/js-tokens.mjs"; | ||
| import "./_libs/strip-literal.mjs"; | ||
| import "./_libs/unimport.mjs"; | ||
| import "./_libs/picomatch.mjs"; | ||
| import "./_libs/fdir.mjs"; | ||
| import "./_libs/tinyglobby.mjs"; | ||
| import "./_libs/compatx.mjs"; | ||
| import "./_libs/klona.mjs"; | ||
| import "./_libs/std-env.mjs"; | ||
| import "./_chunks/B-D1JOIz.mjs"; | ||
| import "./_libs/escape-string-regexp.mjs"; | ||
| import "./_common.mjs"; | ||
| import { $ as resolveModulePath, B as T, D as prepare, I as prettyPath, O as copyPublicAssets, V as a, at as join$1, ct as resolve$1, d as libChunkName, f as baseBuildConfig, h as writeBuildInfo, it as isAbsolute$1, l as NODE_MODULES_RE, m as getBuildInfo, n as baseBuildPlugins, nt as dirname$1, st as relative$1, tt as basename$1, u as getChunkName } from "./_build/common.mjs"; | ||
| import { i as debounce } from "./_libs/rc9+c12+dotenv.mjs"; | ||
| import { t as formatCompatibilityDate } from "./_libs/compatx.mjs"; | ||
| import { i as createNitro } from "./_chunks/nitro.mjs"; | ||
| import "./_libs/tsconfck.mjs"; | ||
| import "./_libs/dot-prop.mjs"; | ||
| import "./_chunks/C7CbzoI1.mjs"; | ||
| import "./_chunks/ANM1K1bE.mjs"; | ||
| import "./_libs/rou3.mjs"; | ||
| import "./_libs/mime.mjs"; | ||
| import "./_libs/pathe.mjs"; | ||
| import "./_libs/untyped.mjs"; | ||
| import "./_libs/knitwork.mjs"; | ||
| import "./_build/common.mjs"; | ||
| import "./_libs/httpxy.mjs"; | ||
| import "./_dev.mjs"; | ||
| import "./_libs/chokidar.mjs"; | ||
| import "./_libs/ultrahtml.mjs"; | ||
| import "./_libs/plugin-alias.mjs"; | ||
| import "./_libs/estree-walker.mjs"; | ||
| import "./_libs/plugin-commonjs.mjs"; | ||
| import "./_libs/plugin-inject.mjs"; | ||
| import "./_build/common2.mjs"; | ||
| import "./_libs/remapping.mjs"; | ||
| import "./_libs/unwasm.mjs"; | ||
| import "./_libs/plugin-replace.mjs"; | ||
| import "./_libs/etag.mjs"; | ||
| import { t as nitro } from "./_build/vite.plugin.mjs"; | ||
| import "./_libs/vite-plugin-fullstack.mjs"; | ||
| import { n as scanHandlers } from "./_chunks/nitro2.mjs"; | ||
| import { i as NodeEnvRunner, r as NitroDevApp } from "./_chunks/dev.mjs"; | ||
| import { n as watch$1 } from "./_libs/readdirp+chokidar.mjs"; | ||
| import { n as assetsPlugin } from "./_libs/pluginutils.mjs"; | ||
| import consola$1 from "consola"; | ||
| import { existsSync, watch } from "node:fs"; | ||
| import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; | ||
| import { join, resolve } from "node:path"; | ||
| import { defu } from "defu"; | ||
| import { runtimeDependencies, runtimeDir } from "nitro/meta"; | ||
| import { colors } from "consola/utils"; | ||
| import { IncomingMessage } from "node:http"; | ||
| import { NodeRequest, sendNodeResponse } from "srvx/node"; | ||
| import { DevEnvironment } from "vite"; | ||
| import { spawn } from "node:child_process"; | ||
| //#region src/build/vite/bundler.ts | ||
| const getBundlerConfig = async (ctx) => { | ||
| const nitro$1 = ctx.nitro; | ||
| const base = baseBuildConfig(nitro$1); | ||
| const commonConfig = { | ||
| input: nitro$1.options.entry, | ||
| external: [...base.env.external], | ||
| plugins: [...await baseBuildPlugins(nitro$1, base)].filter(Boolean), | ||
| treeshake: { moduleSideEffects(id) { | ||
| return nitro$1.options.moduleSideEffects.some((p) => id.startsWith(p)); | ||
| } }, | ||
| onwarn(warning, warn) { | ||
| if (!base.ignoreWarningCodes.has(warning.code || "")) warn(warning); | ||
| }, | ||
| output: { | ||
| dir: nitro$1.options.output.serverDir, | ||
| format: "esm", | ||
| entryFileNames: "index.mjs", | ||
| chunkFileNames: (chunk) => getChunkName(chunk, nitro$1), | ||
| inlineDynamicImports: nitro$1.options.inlineDynamicImports, | ||
| sourcemapIgnoreList: (id) => id.includes("node_modules") | ||
| } | ||
| }; | ||
| if (ctx._isRolldown) return { | ||
| base, | ||
| rollupConfig: void 0, | ||
| rolldownConfig: defu({ | ||
| transform: { inject: base.env.inject }, | ||
| output: { codeSplitting: { groups: [{ | ||
| test: NODE_MODULES_RE, | ||
| name: (id) => libChunkName(id) | ||
| }] } } | ||
| }, nitro$1.options.rolldownConfig, nitro$1.options.rollupConfig, commonConfig) | ||
| }; | ||
| else { | ||
| const inject = (await import("./_libs/plugin-inject.mjs").then((n) => n.t)).default; | ||
| const alias = (await import("./_libs/plugin-alias.mjs").then((n) => n.n)).default; | ||
| return { | ||
| base, | ||
| rolldownConfig: void 0, | ||
| rollupConfig: defu({ | ||
| plugins: [inject(base.env.inject), alias({ entries: base.aliases })], | ||
| output: { | ||
| sourcemapExcludeSources: true, | ||
| generatedCode: { constBindings: true }, | ||
| manualChunks(id) { | ||
| if (NODE_MODULES_RE.test(id)) return libChunkName(id); | ||
| } | ||
| } | ||
| }, nitro$1.options.rolldownConfig, nitro$1.options.rollupConfig, commonConfig) | ||
| }; | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/build/vite/prod.ts | ||
| const BuilderNames = { | ||
| nitro: colors.magenta("Nitro"), | ||
| client: colors.green("Client"), | ||
| ssr: colors.blue("SSR") | ||
| }; | ||
| async function buildEnvironments(ctx, builder) { | ||
| const nitro$1 = ctx.nitro; | ||
| for (const [envName, env] of Object.entries(builder.environments)) { | ||
| const fmtName = BuilderNames[envName] || (envName.length <= 3 ? envName.toUpperCase() : envName[0].toUpperCase() + envName.slice(1)); | ||
| if (envName === "nitro" || !env.config.build.rollupOptions.input || env.isBuilt) { | ||
| if (![ | ||
| "nitro", | ||
| "ssr", | ||
| "client" | ||
| ].includes(envName)) nitro$1.logger.info(env.isBuilt ? `Skipping ${fmtName} (already built)` : `Skipping ${fmtName} (no input defined)`); | ||
| continue; | ||
| } | ||
| if (!a && !T) console.log(); | ||
| nitro$1.logger.start(`Building [${fmtName}]`); | ||
| await builder.build(env); | ||
| } | ||
| const nitroOptions = ctx.nitro.options; | ||
| const clientInput = builder.environments.client?.config?.build?.rollupOptions?.input; | ||
| if (nitroOptions.renderer?.template && nitroOptions.renderer?.template === clientInput) { | ||
| const outputPath = resolve$1(nitroOptions.output.publicDir, basename$1(clientInput)); | ||
| if (existsSync(outputPath)) { | ||
| const html = await readFile(outputPath, "utf8").then((r) => r.replace("<!--ssr-outlet-->", `{{{ globalThis.__nitro_vite_envs__?.["ssr"]?.fetch($REQUEST) || "" }}}`)); | ||
| await rm(outputPath); | ||
| const tmp = resolve$1(nitroOptions.buildDir, "vite/index.html"); | ||
| await mkdir(dirname$1(tmp), { recursive: true }); | ||
| await writeFile(tmp, html, "utf8"); | ||
| nitroOptions.renderer.template = tmp; | ||
| } | ||
| } | ||
| await builder.writeAssetsManifest?.(); | ||
| if (!a && !T) console.log(); | ||
| const buildInfo = [["preset", nitro$1.options.preset], ["compatibility", formatCompatibilityDate(nitro$1.options.compatibilityDate)]].filter((e) => e[1]); | ||
| nitro$1.logger.start(`Building [${BuilderNames.nitro}] ${colors.dim(`(${buildInfo.map(([k, v]) => `${k}: \`${v}\``).join(", ")})`)}`); | ||
| await copyPublicAssets(nitro$1); | ||
| const assetDirs = new Set(Object.values(builder.environments).filter((env) => env.config.consumer === "client").map((env) => env.config.build.assetsDir).filter(Boolean)); | ||
| for (const assetsDir of assetDirs) { | ||
| if (!existsSync(resolve$1(nitro$1.options.output.publicDir, assetsDir))) continue; | ||
| const rule = ctx.nitro.options.routeRules[`/${assetsDir}/**`] ??= {}; | ||
| if (!rule.headers?.["cache-control"]) rule.headers = { | ||
| ...rule.headers, | ||
| "cache-control": `public, max-age=31536000, immutable` | ||
| }; | ||
| } | ||
| ctx.nitro.routing.sync(); | ||
| await builder.build(builder.environments.nitro); | ||
| await nitro$1.close(); | ||
| await nitro$1.hooks.callHook("compiled", nitro$1); | ||
| await writeBuildInfo(nitro$1); | ||
| const rOutput = relative$1(process.cwd(), nitro$1.options.output.dir); | ||
| const rewriteRelativePaths = (input) => { | ||
| return input.replace(/([\s:])\.\/(\S*)/g, `$1${rOutput}/$2`); | ||
| }; | ||
| if (!a && !T) console.log(); | ||
| if (nitro$1.options.commands.preview) nitro$1.logger.success(`You can preview this build using \`${rewriteRelativePaths(nitro$1.options.commands.preview)}\``); | ||
| if (nitro$1.options.commands.deploy) nitro$1.logger.success(`You can deploy this build using \`${rewriteRelativePaths(nitro$1.options.commands.deploy)}\``); | ||
| } | ||
| function prodSetup(ctx) { | ||
| return ` | ||
| function lazyService(loader) { | ||
| let promise, mod | ||
| return { | ||
| fetch(req) { | ||
| if (mod) { return mod.fetch(req) } | ||
| if (!promise) { | ||
| promise = loader().then(_mod => (mod = _mod.default || _mod)) | ||
| } | ||
| return promise.then(mod => mod.fetch(req)) | ||
| } | ||
| } | ||
| } | ||
| const services = { | ||
| ${Object.keys(ctx.services).map((name) => { | ||
| return [name, resolve$1(ctx.nitro.options.buildDir, "vite/services", name, ctx._entryPoints[name])]; | ||
| }).map(([name, entry]) => `[${JSON.stringify(name)}]: lazyService(() => import(${JSON.stringify(entry)}))`).join(",\n")} | ||
| }; | ||
| globalThis.__nitro_vite_envs__ = services; | ||
| `; | ||
| } | ||
| //#endregion | ||
| //#region src/build/vite/dev.ts | ||
| function createFetchableDevEnvironment(name, config, devServer, entry) { | ||
| return new FetchableDevEnvironment(name, config, { | ||
| hot: true, | ||
| transport: createTransport(name, devServer) | ||
| }, devServer, entry); | ||
| } | ||
| var FetchableDevEnvironment = class extends DevEnvironment { | ||
| devServer; | ||
| constructor(name, config, context, devServer, entry) { | ||
| super(name, config, context); | ||
| this.devServer = devServer; | ||
| this.devServer.sendMessage({ | ||
| type: "custom", | ||
| event: "nitro:vite-env", | ||
| data: { | ||
| name, | ||
| entry | ||
| } | ||
| }); | ||
| } | ||
| async dispatchFetch(request) { | ||
| return this.devServer.fetch(request); | ||
| } | ||
| async init(...args) { | ||
| await this.devServer.init?.(); | ||
| return super.init(...args); | ||
| } | ||
| }; | ||
| function createTransport(name, hooks) { | ||
| const listeners = /* @__PURE__ */ new WeakMap(); | ||
| return { | ||
| send: (data) => hooks.sendMessage({ | ||
| ...data, | ||
| viteEnv: name | ||
| }), | ||
| on: (event, handler) => { | ||
| if (event === "connection") return; | ||
| const listener = (value) => { | ||
| if (value?.type === "custom" && value.event === event && value.viteEnv === name) handler(value.data, { send: (payload) => hooks.sendMessage({ | ||
| ...payload, | ||
| viteEnv: name | ||
| }) }); | ||
| }; | ||
| listeners.set(handler, listener); | ||
| hooks.onMessage(listener); | ||
| }, | ||
| off: (event, handler) => { | ||
| if (event === "connection") return; | ||
| const listener = listeners.get(handler); | ||
| if (listener) { | ||
| hooks.offMessage(listener); | ||
| listeners.delete(handler); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| async function configureViteDevServer(ctx, server) { | ||
| const nitro$1 = ctx.nitro; | ||
| const nitroEnv$1 = server.environments.nitro; | ||
| const nitroConfigFile = nitro$1.options._c12.configFile; | ||
| if (nitroConfigFile) server.config.configFileDependencies.push(nitroConfigFile); | ||
| if (nitro$1.options.features.websocket ?? nitro$1.options.experimental.websocket) server.httpServer.on("upgrade", (req, socket, head) => { | ||
| if (req.url?.startsWith("/?token")) return; | ||
| getEnvRunner(ctx).upgrade?.(req, socket, head); | ||
| }); | ||
| const reload = debounce(async () => { | ||
| await scanHandlers(nitro$1); | ||
| nitro$1.routing.sync(); | ||
| nitroEnv$1.moduleGraph.invalidateAll(); | ||
| nitroEnv$1.hot.send({ type: "full-reload" }); | ||
| }); | ||
| const scanDirs = nitro$1.options.scanDirs.flatMap((dir) => [ | ||
| join$1(dir, nitro$1.options.apiDir || "api"), | ||
| join$1(dir, nitro$1.options.routesDir || "routes"), | ||
| join$1(dir, "middleware"), | ||
| join$1(dir, "plugins"), | ||
| join$1(dir, "modules") | ||
| ]); | ||
| const watchReloadEvents = new Set([ | ||
| "add", | ||
| "addDir", | ||
| "unlink", | ||
| "unlinkDir" | ||
| ]); | ||
| const scanDirsWatcher = watch$1(scanDirs, { ignoreInitial: true }).on("all", (event, path$1, stat$2) => { | ||
| if (watchReloadEvents.has(event)) reload(); | ||
| }); | ||
| const rootDirWatcher = watch(nitro$1.options.rootDir, { persistent: false }, (_event, filename) => { | ||
| if (filename && /^server\.[mc]?[jt]sx?$/.test(filename)) reload(); | ||
| }); | ||
| nitro$1.hooks.hook("close", () => { | ||
| scanDirsWatcher.close(); | ||
| rootDirWatcher.close(); | ||
| }); | ||
| const hostIPC = { async transformHTML(html) { | ||
| return server.transformIndexHtml("/", html).then((r) => r.replace("<!--ssr-outlet-->", `{{{ globalThis.__nitro_vite_envs__?.["ssr"]?.fetch($REQUEST) || "" }}}`)); | ||
| } }; | ||
| nitroEnv$1.devServer.onMessage(async (payload) => { | ||
| if (payload.type === "custom" && payload.event === "nitro:vite-invoke") { | ||
| const res = await hostIPC[payload.data.name](payload.data.data).then((data) => ({ data })).catch((error) => ({ error })); | ||
| nitroEnv$1.devServer.sendMessage({ | ||
| type: "custom", | ||
| event: "nitro:vite-invoke-response", | ||
| data: { | ||
| id: payload.data.id, | ||
| data: res | ||
| } | ||
| }); | ||
| } | ||
| }); | ||
| const nitroDevMiddleware = async (nodeReq, nodeRes, next) => { | ||
| if (!nodeReq.url || /^\/@(?:vite|fs|id)\//.test(nodeReq.url) || nodeReq._nitroHandled || server.middlewares.stack.map((mw) => mw.route).some((base) => base && nodeReq.url.startsWith(base))) return next(); | ||
| nodeReq._nitroHandled = true; | ||
| try { | ||
| const req = new NodeRequest({ | ||
| req: nodeReq, | ||
| res: nodeRes | ||
| }); | ||
| const devAppRes = await ctx.devApp.fetch(req); | ||
| if (nodeRes.writableEnded || nodeRes.headersSent) return; | ||
| if (devAppRes.status !== 404) return await sendNodeResponse(nodeRes, devAppRes); | ||
| const envRes = await nitroEnv$1.dispatchFetch(req); | ||
| if (nodeRes.writableEnded || nodeRes.headersSent) return; | ||
| return await sendNodeResponse(nodeRes, envRes); | ||
| } catch (error) { | ||
| return next(error); | ||
| } | ||
| }; | ||
| server.middlewares.use(function nitroDevMiddlewarePre(req, res, next) { | ||
| const fetchDest = req.headers["sec-fetch-dest"]; | ||
| res.setHeader("vary", "sec-fetch-dest"); | ||
| if ((!fetchDest || /^(document|iframe|frame|empty)$/.test(fetchDest)) && !req.url.match(/\.([a-z0-9]+)(?:[?#]|$)/i)?.[1] && !/^\/(?:__|@)/.test(req.url)) nitroDevMiddleware(req, res, next); | ||
| else next(); | ||
| }); | ||
| return () => { | ||
| server.middlewares.use(nitroDevMiddleware); | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/build/vite/env.ts | ||
| function getEnvRunner(ctx) { | ||
| return ctx._envRunner ??= new NodeEnvRunner({ | ||
| name: "nitro-vite", | ||
| entry: resolve(runtimeDir, "internal/vite/node-runner.mjs"), | ||
| data: { server: true } | ||
| }); | ||
| } | ||
| function createNitroEnvironment(ctx) { | ||
| return { | ||
| consumer: "server", | ||
| build: { | ||
| rollupOptions: ctx.bundlerConfig.rollupConfig, | ||
| rolldownOptions: ctx.bundlerConfig.rolldownConfig, | ||
| minify: ctx.nitro.options.minify, | ||
| emptyOutDir: false, | ||
| sourcemap: ctx.nitro.options.sourcemap, | ||
| commonjsOptions: ctx.nitro.options.commonJS | ||
| }, | ||
| resolve: { | ||
| noExternal: ctx.nitro.options.dev ? [ | ||
| /^nitro$/, | ||
| /* @__PURE__ */ new RegExp(`^(${runtimeDependencies.join("|")})$`), | ||
| ...ctx.bundlerConfig.base.noExternal | ||
| ] : true, | ||
| conditions: ctx.nitro.options.exportConditions, | ||
| externalConditions: ctx.nitro.options.exportConditions?.filter((c) => !/browser|wasm|module/.test(c)) | ||
| }, | ||
| define: { "process.env.NODE_ENV": JSON.stringify(ctx.nitro.options.dev ? "development" : "production") }, | ||
| dev: { createEnvironment: (envName, envConfig) => createFetchableDevEnvironment(envName, envConfig, getEnvRunner(ctx), resolve(runtimeDir, "internal/vite/dev-entry.mjs")) } | ||
| }; | ||
| } | ||
| function createServiceEnvironment(ctx, name, serviceConfig) { | ||
| return { | ||
| consumer: "server", | ||
| build: { | ||
| rollupOptions: { input: { index: serviceConfig.entry } }, | ||
| minify: ctx.nitro.options.minify, | ||
| sourcemap: ctx.nitro.options.sourcemap, | ||
| outDir: join(ctx.nitro.options.buildDir, "vite/services", name), | ||
| emptyOutDir: true | ||
| }, | ||
| resolve: { | ||
| conditions: ctx.nitro.options.exportConditions, | ||
| externalConditions: ctx.nitro.options.exportConditions?.filter((c) => !/browser|wasm|module/.test(c)) | ||
| }, | ||
| dev: { createEnvironment: (envName, envConfig) => createFetchableDevEnvironment(envName, envConfig, getEnvRunner(ctx), tryResolve(serviceConfig.entry)) } | ||
| }; | ||
| } | ||
| function createServiceEnvironments(ctx) { | ||
| return Object.fromEntries(Object.entries(ctx.services).map(([name, config]) => [name, createServiceEnvironment(ctx, name, config)])); | ||
| } | ||
| function tryResolve(id) { | ||
| if (/^[~#/\0]/.test(id) || isAbsolute$1(id)) return id; | ||
| return resolveModulePath(id, { | ||
| suffixes: ["", "/index"], | ||
| extensions: [ | ||
| "", | ||
| ".ts", | ||
| ".mjs", | ||
| ".cjs", | ||
| ".js", | ||
| ".mts", | ||
| ".cts" | ||
| ], | ||
| try: true | ||
| }) || id; | ||
| } | ||
| //#endregion | ||
| //#region src/build/vite/preview.ts | ||
| function nitroPreviewPlugin(ctx) { | ||
| return { | ||
| name: "nitro:preview", | ||
| apply: (_config, configEnv) => !!configEnv.isPreview, | ||
| config(config) { | ||
| return { preview: { port: config.preview?.port || 3e3 } }; | ||
| }, | ||
| async configurePreviewServer(server) { | ||
| const { outputDir, buildInfo } = await getBuildInfo(server.config.root); | ||
| if (!buildInfo) throw this.error("Cannot load nitro build info. Make sure to build first."); | ||
| const info = [ | ||
| ["Build Directory:", prettyPath(outputDir)], | ||
| ["Date:", buildInfo.date && new Date(buildInfo.date).toLocaleString()], | ||
| ["Nitro Version:", buildInfo.versions.nitro], | ||
| ["Nitro Preset:", buildInfo.preset], | ||
| buildInfo.framework?.name !== "nitro" && ["Framework:", buildInfo.framework?.name + (buildInfo.framework?.version ? ` (v${buildInfo.framework.version})` : "")] | ||
| ].filter((i) => i && i[1]); | ||
| consola$1.box({ | ||
| title: " [Build Info] ", | ||
| message: info.map((i) => `- ${i[0]} ${i[1]}`).join("\n") | ||
| }); | ||
| if (!buildInfo.commands?.preview) { | ||
| consola$1.warn("No nitro build preview command found for this preset."); | ||
| return; | ||
| } | ||
| const dotEnvEntries = await loadPreviewDotEnv(server.config.root); | ||
| if (dotEnvEntries.length > 0) consola$1.box({ | ||
| title: " [Environment Variables] ", | ||
| message: [ | ||
| "Loaded variables from .env files (preview mode only).", | ||
| "Set platform environment variables for production:", | ||
| ...dotEnvEntries.map(([key, val]) => ` - ${key}`) | ||
| ].join("\n") | ||
| }); | ||
| const [command, ...args] = buildInfo.commands.preview.split(" "); | ||
| consola$1.info(`Spawning preview server...`); | ||
| consola$1.info(buildInfo.commands?.preview); | ||
| console.log(""); | ||
| const { getRandomPort, waitForPort } = await import("get-port-please"); | ||
| const randomPort = await getRandomPort(); | ||
| const child = spawn(command, args, { | ||
| stdio: "inherit", | ||
| cwd: outputDir, | ||
| env: { | ||
| ...process.env, | ||
| ...Object.fromEntries(dotEnvEntries), | ||
| PORT: String(randomPort) | ||
| } | ||
| }); | ||
| const killChild = (signal) => { | ||
| if (child && !child.killed) child.kill(signal); | ||
| }; | ||
| for (const sig of ["SIGINT", "SIGHUP"]) process.once(sig, () => { | ||
| consola$1.info(`Stopping preview server...`); | ||
| killChild(sig); | ||
| process.exit(); | ||
| }); | ||
| server.httpServer.once("close", () => { | ||
| killChild("SIGTERM"); | ||
| }); | ||
| child.once("exit", (code) => { | ||
| if (code && code !== 0) consola$1.error(`[nitro] Preview server exited with code ${code}`); | ||
| }); | ||
| const { createProxyServer } = await import("./_libs/httpxy.mjs").then((n) => n.n); | ||
| const proxy = createProxyServer({ target: `http://localhost:${randomPort}` }); | ||
| server.middlewares.use((req, res, next) => { | ||
| if (child && !child.killed) proxy.web(req, res).catch(next); | ||
| else res.end(`Nitro preview server is not running.`); | ||
| }); | ||
| await waitForPort(randomPort, { | ||
| retries: 20, | ||
| delay: 500 | ||
| }); | ||
| } | ||
| }; | ||
| } | ||
| async function loadPreviewDotEnv(root) { | ||
| const { loadDotenv } = await import("./_libs/rc9+c12+dotenv.mjs").then((n) => n.t); | ||
| const env = await loadDotenv({ | ||
| cwd: root, | ||
| fileName: [ | ||
| ".env.preview", | ||
| ".env.production", | ||
| ".env" | ||
| ] | ||
| }); | ||
| return Object.entries(env).filter(([_key, val]) => val); | ||
| } | ||
| //#endregion | ||
| //#region src/build/vite/plugin.ts | ||
| const DEFAULT_EXTENSIONS = [ | ||
| ".ts", | ||
| ".js", | ||
| ".mts", | ||
| ".mjs", | ||
| ".tsx", | ||
| ".jsx" | ||
| ]; | ||
| const debug = process.env.NITRO_DEBUG ? (...args) => console.log("[nitro]", ...args) : () => {}; | ||
| function nitro(pluginConfig = {}) { | ||
| const ctx = createContext(pluginConfig); | ||
| return [ | ||
| nitroInit(ctx), | ||
| nitroEnv(ctx), | ||
| nitroMain(ctx), | ||
| nitroPrepare(ctx), | ||
| nitroService(ctx), | ||
| nitroPreviewPlugin(ctx), | ||
| pluginConfig.experimental?.vite?.assetsImport !== false && assetsPlugin({ experimental: { clientBuildFallback: false } }) | ||
| ].filter(Boolean); | ||
| } | ||
| function nitroInit(ctx) { | ||
| return { | ||
| name: "nitro:init", | ||
| sharedDuringBuild: true, | ||
| apply: (_config, configEnv) => !configEnv.isPreview, | ||
| async config(config, configEnv) { | ||
| ctx._isRolldown = !!this.meta.rolldownVersion; | ||
| if (!ctx._initialized) { | ||
| debug("[init] Initializing nitro"); | ||
| ctx._initialized = true; | ||
| await setupNitroContext(ctx, configEnv, config); | ||
| } | ||
| }, | ||
| applyToEnvironment(env) { | ||
| if (env.name === "nitro" && ctx.nitro?.options.dev) { | ||
| debug("[init] Adding rollup plugins for dev"); | ||
| return [...ctx.bundlerConfig?.rolldownConfig?.plugins || ctx.bundlerConfig?.rollupConfig?.plugins || []]; | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function nitroEnv(ctx) { | ||
| return { | ||
| name: "nitro:env", | ||
| sharedDuringBuild: true, | ||
| apply: (_config, configEnv) => !configEnv.isPreview, | ||
| async config(userConfig, _configEnv) { | ||
| debug("[env] Extending config (environments)"); | ||
| const environments = { | ||
| ...createServiceEnvironments(ctx), | ||
| nitro: createNitroEnvironment(ctx) | ||
| }; | ||
| environments.client = { | ||
| consumer: userConfig.environments?.client?.consumer ?? "client", | ||
| build: { rollupOptions: { input: userConfig.environments?.client?.build?.rollupOptions?.input ?? useNitro(ctx).options.renderer?.template } } | ||
| }; | ||
| debug("[env] Environments:", Object.keys(environments).join(", ")); | ||
| return { environments }; | ||
| }, | ||
| configEnvironment(name, config) { | ||
| if (config.consumer === "client") { | ||
| debug("[env] Configuring client environment", name === "client" ? "" : ` (${name})`); | ||
| config.build.emptyOutDir = false; | ||
| config.build.outDir = useNitro(ctx).options.output.publicDir; | ||
| return; | ||
| } | ||
| if (name === "nitro" || ctx.services[name]) return; | ||
| const entry = getEntry(config.build?.rolldownOptions?.input || config.build?.rollupOptions?.input); | ||
| if (typeof entry !== "string") return; | ||
| const resolvedEntry = resolveModulePath(entry, { | ||
| from: [ctx.nitro.options.rootDir, ...ctx.nitro.options.scanDirs], | ||
| extensions: DEFAULT_EXTENSIONS, | ||
| suffixes: ["", "/index"], | ||
| try: true | ||
| }) || entry; | ||
| ctx.services[name] = { entry: resolvedEntry }; | ||
| debug(`[env] Auto-detected service "${name}" with entry: ${resolvedEntry}`); | ||
| return createServiceEnvironment(ctx, name, { entry: resolvedEntry }); | ||
| }, | ||
| configResolved() { | ||
| if (!ctx.nitro.options.renderer?.handler && !ctx.nitro.options.renderer?.template && ctx.services.ssr?.entry) { | ||
| ctx.nitro.options.renderer ??= {}; | ||
| ctx.nitro.options.renderer.handler = resolve$1(runtimeDir, "internal/vite/ssr-renderer"); | ||
| ctx.nitro.routing.sync(); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function nitroMain(ctx) { | ||
| return { | ||
| name: "nitro:main", | ||
| sharedDuringBuild: true, | ||
| apply: (_config, configEnv) => !configEnv.isPreview, | ||
| async config(userConfig, _configEnv) { | ||
| debug("[main] Extending config (appType, resolve, server)"); | ||
| if (!ctx.bundlerConfig) throw new Error("Bundler config is not initialized yet!"); | ||
| return { | ||
| appType: userConfig.appType || "custom", | ||
| resolve: { alias: ctx.bundlerConfig.base.aliases }, | ||
| builder: { sharedConfigBuild: true }, | ||
| server: { | ||
| port: Number.parseInt(process.env.PORT || "") || userConfig.server?.port || useNitro(ctx).options.devServer?.port || 3e3, | ||
| cors: false | ||
| } | ||
| }; | ||
| }, | ||
| buildApp: { | ||
| order: "post", | ||
| handler(builder) { | ||
| debug("[main] Building environments"); | ||
| return buildEnvironments(ctx, builder); | ||
| } | ||
| }, | ||
| generateBundle: { handler(_options, bundle) { | ||
| const environment = this.environment; | ||
| debug("[main] Generating manifest and entry points for environment:", environment.name); | ||
| const isRegisteredService = Object.keys(ctx.services).includes(environment.name); | ||
| let entryFile; | ||
| for (const [_name, file] of Object.entries(bundle)) if (file.type === "chunk" && isRegisteredService && file.isEntry) if (entryFile === void 0) entryFile = file.fileName; | ||
| else this.warn(`Multiple entry points found for service "${environment.name}"`); | ||
| if (isRegisteredService) { | ||
| if (entryFile === void 0) this.error(`No entry point found for service "${this.environment.name}".`); | ||
| ctx._entryPoints[this.environment.name] = entryFile; | ||
| } | ||
| } }, | ||
| configureServer: (server) => { | ||
| debug("[main] Configuring dev server"); | ||
| return configureViteDevServer(ctx, server); | ||
| }, | ||
| async hotUpdate({ server, modules, timestamp }) { | ||
| const env = this.environment; | ||
| if (ctx.pluginConfig.experimental?.vite.serverReload === false || env.config.consumer === "client") return; | ||
| const clientEnvs = Object.values(server.environments).filter((env$1) => env$1.config.consumer === "client"); | ||
| let hasServerOnlyModule = false; | ||
| const invalidated = /* @__PURE__ */ new Set(); | ||
| for (const mod of modules) if (mod.id && !clientEnvs.some((env$1) => env$1.moduleGraph.getModuleById(mod.id))) { | ||
| hasServerOnlyModule = true; | ||
| env.moduleGraph.invalidateModule(mod, invalidated, timestamp, false); | ||
| } | ||
| if (hasServerOnlyModule) { | ||
| env.hot.send({ type: "full-reload" }); | ||
| server.ws.send({ type: "full-reload" }); | ||
| return []; | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function nitroPrepare(ctx) { | ||
| return { | ||
| name: "nitro:prepare", | ||
| sharedDuringBuild: true, | ||
| applyToEnvironment: (env) => env.name === "nitro", | ||
| buildApp: { | ||
| order: "pre", | ||
| async handler() { | ||
| debug("[prepare] Preparing output directory"); | ||
| const nitro = ctx.nitro; | ||
| await prepare(nitro); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function nitroService(ctx) { | ||
| return { | ||
| name: "nitro:service", | ||
| enforce: "pre", | ||
| sharedDuringBuild: true, | ||
| applyToEnvironment: (env) => env.name === "nitro", | ||
| resolveId: { | ||
| filter: { id: /^#nitro-vite-setup$/ }, | ||
| async handler(id) { | ||
| if (id === "#nitro-vite-setup") return { | ||
| id, | ||
| moduleSideEffects: true | ||
| }; | ||
| } | ||
| }, | ||
| load: { | ||
| filter: { id: /^#nitro-vite-setup$/ }, | ||
| async handler(id) { | ||
| if (id === "#nitro-vite-setup") return prodSetup(ctx); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function createContext(pluginConfig) { | ||
| return { | ||
| pluginConfig, | ||
| services: { ...pluginConfig.experimental?.vite?.services }, | ||
| _entryPoints: {} | ||
| }; | ||
| } | ||
| function useNitro(ctx) { | ||
| if (!ctx.nitro) throw new Error("Nitro instance is not initialized yet."); | ||
| return ctx.nitro; | ||
| } | ||
| async function setupNitroContext(ctx, configEnv, userConfig) { | ||
| const nitroConfig = { | ||
| dev: configEnv.command === "serve", | ||
| builder: "vite", | ||
| rootDir: userConfig.root, | ||
| ...defu(ctx.pluginConfig, ctx.pluginConfig.config, userConfig.nitro) | ||
| }; | ||
| nitroConfig.modules ??= []; | ||
| for (const plugin of flattenPlugins(userConfig.plugins || [])) if (plugin.nitro) nitroConfig.modules.push(plugin.nitro); | ||
| ctx.nitro = ctx.pluginConfig._nitro || await createNitro(nitroConfig); | ||
| if (!ctx.services?.ssr) if (userConfig.environments?.ssr === void 0) { | ||
| const ssrEntry = resolveModulePath("./entry-server", { | ||
| from: [ | ||
| "app", | ||
| "src", | ||
| "" | ||
| ].flatMap((d) => [ctx.nitro.options.rootDir, ...ctx.nitro.options.scanDirs].map((s) => join$1(s, d) + "/")), | ||
| extensions: DEFAULT_EXTENSIONS, | ||
| try: true | ||
| }); | ||
| if (ssrEntry) { | ||
| ctx.services.ssr = { entry: ssrEntry }; | ||
| ctx.nitro.logger.info(`Using \`${prettyPath(ssrEntry)}\` as vite ssr entry.`); | ||
| } | ||
| } else { | ||
| let ssrEntry = getEntry(userConfig.environments.ssr.build?.rollupOptions?.input); | ||
| if (typeof ssrEntry === "string") { | ||
| ssrEntry = resolveModulePath(ssrEntry, { | ||
| from: [ctx.nitro.options.rootDir, ...ctx.nitro.options.scanDirs], | ||
| extensions: DEFAULT_EXTENSIONS, | ||
| suffixes: ["", "/index"], | ||
| try: true | ||
| }) || ssrEntry; | ||
| ctx.services.ssr = { entry: ssrEntry }; | ||
| } | ||
| } | ||
| if (ctx.nitro.options.serverEntry && ctx.nitro.options.serverEntry.handler === ctx.services.ssr?.entry) { | ||
| ctx.nitro.logger.warn(`Nitro server entry and Vite SSR both set to ${prettyPath(ctx.services.ssr.entry)}. Use a separate SSR entry (e.g. \`src/server.ts\`).`); | ||
| ctx.nitro.options.serverEntry = false; | ||
| } | ||
| const publicDistDir = ctx._publicDistDir = userConfig.build?.outDir || resolve$1(ctx.nitro.options.buildDir, "vite/public"); | ||
| ctx.nitro.options.publicAssets.push({ | ||
| dir: publicDistDir, | ||
| maxAge: 0, | ||
| baseURL: "/", | ||
| fallthrough: true | ||
| }); | ||
| if (!ctx.nitro.options.dev) ctx.nitro.options.unenv.push({ | ||
| meta: { name: "nitro-vite" }, | ||
| polyfill: ["#nitro-vite-setup"] | ||
| }); | ||
| await ctx.nitro.hooks.callHook("build:before", ctx.nitro); | ||
| ctx.bundlerConfig = await getBundlerConfig(ctx); | ||
| await ctx.nitro.hooks.callHook("rollup:before", ctx.nitro, ctx.bundlerConfig.rollupConfig || ctx.bundlerConfig.rolldownConfig); | ||
| if (ctx.nitro.options.dev) getEnvRunner(ctx); | ||
| ctx.nitro.fetch = (req) => getEnvRunner(ctx).fetch(req); | ||
| if (ctx.nitro.options.dev && !ctx.devApp) ctx.devApp = new NitroDevApp(ctx.nitro); | ||
| ctx.nitro.hooks.hook("close", async () => { | ||
| if (ctx._envRunner) await ctx._envRunner.close(); | ||
| }); | ||
| } | ||
| function getEntry(input) { | ||
| if (typeof input === "string") return input; | ||
| else if (Array.isArray(input) && input.length > 0) return input[0]; | ||
| else if (input && "index" in input) return input.index; | ||
| } | ||
| function flattenPlugins(plugins) { | ||
| return plugins.flatMap((plugin) => Array.isArray(plugin) ? flattenPlugins(plugin) : [plugin]).filter((p) => p && !(p instanceof Promise)); | ||
| } | ||
| //#endregion | ||
| export { nitro }; |
+82
-53
| { | ||
| "name": "nitro", | ||
| "version": "3.0.1-alpha.1", | ||
| "version": "3.0.1-alpha.2", | ||
| "description": "Build and Deploy Universal JavaScript Servers", | ||
| "keywords": [ | ||
| "api-routes", | ||
| "full-stack", | ||
| "h3", | ||
| "nitro", | ||
| "server", | ||
| "typescript", | ||
| "vite", | ||
| "vite-plugin", | ||
| "web" | ||
| ], | ||
| "homepage": "https://nitro.build", | ||
@@ -9,2 +20,6 @@ "repository": "nitrojs/nitro", | ||
| "type": "module", | ||
| "imports": { | ||
| "#nitro/runtime/*": "./dist/runtime/internal/*.mjs", | ||
| "#nitro/virtual/*": "./dist/runtime/virtual/*.mjs" | ||
| }, | ||
| "exports": { | ||
@@ -18,5 +33,3 @@ ".": "./dist/runtime/nitro.mjs", | ||
| "./database": "./dist/runtime/database.mjs", | ||
| "./deps/h3": "./lib/deps/h3.mjs", | ||
| "./deps/ofetch": "./lib/deps/ofetch.mjs", | ||
| "./h3": "./lib/deps/h3.mjs", | ||
| "./h3": "./lib/h3.mjs", | ||
| "./meta": "./dist/runtime/meta.mjs", | ||
@@ -30,4 +43,4 @@ "./package.json": "./package.json", | ||
| "./vite": "./dist/vite.mjs", | ||
| "./vite/runtime": "./dist/runtime/vite-runtime.mjs", | ||
| "./~internal/runtime/*": "./dist/runtime/internal/*.mjs" | ||
| "./vite/runtime": "./dist/runtime/vite.mjs", | ||
| "./vite/types": "./lib/vite.types.mjs" | ||
| }, | ||
@@ -55,4 +68,4 @@ "types": "./lib/index.d.mts", | ||
| "test": "pnpm lint && pnpm test:types && pnpm test:rollup && pnpm test:rolldown", | ||
| "test:rolldown": "NITRO_BUILDER=rolldown pnpm vitest", | ||
| "test:rollup": "NITRO_BUILDER=rollup pnpm vitest", | ||
| "test:rolldown": "NITRO_BUILDER=rolldown pnpm vitest", | ||
| "test:types": "tsc --noEmit" | ||
@@ -62,19 +75,19 @@ }, | ||
| "nitro": "link:.", | ||
| "undici": "^7.11.0" | ||
| "undici": "^7.18.2" | ||
| }, | ||
| "dependencies": { | ||
| "consola": "^3.4.2", | ||
| "crossws": "^0.4.1", | ||
| "crossws": "^0.4.3", | ||
| "db0": "^0.3.4", | ||
| "h3": "2.0.1-rc.5", | ||
| "h3": "^2.0.1-rc.11", | ||
| "jiti": "^2.6.1", | ||
| "nf3": "^0.1.10", | ||
| "nf3": "^0.3.5", | ||
| "ofetch": "^2.0.0-alpha.3", | ||
| "ohash": "^2.0.11", | ||
| "oxc-minify": "^0.96.0", | ||
| "oxc-transform": "^0.96.0", | ||
| "srvx": "^0.9.5", | ||
| "undici": "^7.16.0", | ||
| "oxc-minify": "^0.110.0", | ||
| "oxc-transform": "^0.110.0", | ||
| "srvx": "^0.10.1", | ||
| "undici": "^7.18.2", | ||
| "unenv": "^2.0.0-rc.24", | ||
| "unstorage": "^2.0.0-alpha.4" | ||
| "unstorage": "^2.0.0-alpha.5" | ||
| }, | ||
@@ -84,8 +97,7 @@ "devDependencies": { | ||
| "@azure/static-web-apps-cli": "^2.0.7", | ||
| "@cloudflare/workers-types": "^4.20251109.0", | ||
| "@cloudflare/workers-types": "^4.20260120.0", | ||
| "@deno/types": "^0.0.1", | ||
| "rollup": "^4.53.2", | ||
| "@hiogawa/vite-plugin-fullstack": "npm:@pi0/vite-plugin-fullstack@0.0.5-pr-1297", | ||
| "@netlify/edge-functions": "^3.0.2", | ||
| "@netlify/functions": "^5.1.0", | ||
| "@hiogawa/vite-plugin-fullstack": "^0.0.11", | ||
| "@netlify/edge-functions": "^3.0.3", | ||
| "@netlify/functions": "^5.1.2", | ||
| "@rollup/plugin-alias": "^6.0.0", | ||
@@ -97,4 +109,4 @@ "@rollup/plugin-commonjs": "^29.0.0", | ||
| "@rollup/plugin-replace": "^6.0.3", | ||
| "@scalar/api-reference": "^1.39.3", | ||
| "@types/aws-lambda": "^8.10.157", | ||
| "@scalar/api-reference": "^1.43.8", | ||
| "@types/aws-lambda": "^8.10.160", | ||
| "@types/estree": "^1.0.8", | ||
@@ -104,12 +116,12 @@ "@types/etag": "^1.8.4", | ||
| "@types/http-proxy": "^1.17.17", | ||
| "@types/node": "^24.10.0", | ||
| "@types/node": "^25.0.9", | ||
| "@types/node-fetch": "^2.6.13", | ||
| "@types/semver": "^7.7.1", | ||
| "@types/xml2js": "^0.4.14", | ||
| "@vitest/coverage-v8": "^4.0.8", | ||
| "@vitest/coverage-v8": "^4.0.17", | ||
| "automd": "^0.4.2", | ||
| "c12": "^3.3.1", | ||
| "c12": "^3.3.3", | ||
| "changelogen": "^0.6.2", | ||
| "chokidar": "^4.0.3", | ||
| "citty": "^0.1.6", | ||
| "chokidar": "^5.0.0", | ||
| "citty": "^0.2.0", | ||
| "compatx": "^0.2.0", | ||
@@ -124,31 +136,31 @@ "confbox": "^0.2.2", | ||
| "escape-string-regexp": "^5.0.0", | ||
| "eslint": "^9.39.1", | ||
| "eslint-config-unjs": "^0.5.0", | ||
| "eslint": "^9.39.2", | ||
| "eslint-config-unjs": "^0.6.2", | ||
| "etag": "^1.8.1", | ||
| "execa": "^9.6.0", | ||
| "expect-type": "^1.2.2", | ||
| "execa": "^9.6.1", | ||
| "expect-type": "^1.3.0", | ||
| "exsolve": "^1.0.8", | ||
| "fs-extra": "^11.3.2", | ||
| "fs-extra": "^11.3.3", | ||
| "get-port-please": "^3.2.0", | ||
| "gzip-size": "^7.0.0", | ||
| "hookable": "6.0.0-rc.1", | ||
| "hookable": "^6.0.1", | ||
| "httpxy": "^0.1.7", | ||
| "klona": "^2.0.6", | ||
| "knitwork": "^1.2.0", | ||
| "knitwork": "^1.3.0", | ||
| "magic-string": "^0.30.21", | ||
| "mime": "^4.1.0", | ||
| "miniflare": "^4.20251105.0", | ||
| "miniflare": "^4.20260114.0", | ||
| "mlly": "^1.8.0", | ||
| "nypm": "^0.6.2", | ||
| "obuild": "^0.4.1", | ||
| "nypm": "^0.6.4", | ||
| "obuild": "^0.4.18", | ||
| "pathe": "^2.0.3", | ||
| "perfect-debounce": "^2.0.0", | ||
| "pkg-types": "^2.3.0", | ||
| "prettier": "^3.6.2", | ||
| "prettier": "^3.8.0", | ||
| "pretty-bytes": "^7.1.0", | ||
| "react": "^19.2.0", | ||
| "react": "^19.2.3", | ||
| "rendu": "^0.0.7", | ||
| "rolldown": "^1.0.0-beta.47", | ||
| "rolldown-vite": "^7.2.2", | ||
| "rou3": "^0.7.10", | ||
| "rolldown": "1.0.0-beta.60", | ||
| "rollup": "^4.55.2", | ||
| "rou3": "^0.7.12", | ||
| "scule": "^1.3.0", | ||
@@ -162,19 +174,21 @@ "semver": "^7.7.3", | ||
| "typescript": "^5.9.3", | ||
| "ufo": "^1.6.1", | ||
| "ufo": "^1.6.3", | ||
| "ultrahtml": "^1.6.0", | ||
| "uncrypto": "^0.1.3", | ||
| "unctx": "^2.4.1", | ||
| "unimport": "^5.5.0", | ||
| "unctx": "^2.5.0", | ||
| "unimport": "^5.6.0", | ||
| "untyped": "^2.0.0", | ||
| "unwasm": "^0.4.2", | ||
| "vitest": "^4.0.8", | ||
| "wrangler": "^4.46.0", | ||
| "unwasm": "^0.5.3", | ||
| "vite": "8.0.0-beta.8", | ||
| "vite7": "npm:vite@^7.3.1", | ||
| "vitest": "^4.0.17", | ||
| "wrangler": "~4.59.2", | ||
| "xml2js": "^0.6.2", | ||
| "youch": "^4.1.0-beta.12", | ||
| "youch": "4.1.0-beta.13", | ||
| "youch-core": "^0.3.3" | ||
| }, | ||
| "peerDependencies": { | ||
| "rolldown": "*", | ||
| "vite": "^7", | ||
| "rolldown": ">=1.0.0-beta.0", | ||
| "rollup": "^4", | ||
| "vite": "^7 || ^8 || >=8.0.0-0", | ||
| "xml2js": "^0.6.2" | ||
@@ -196,6 +210,21 @@ }, | ||
| }, | ||
| "packageManager": "pnpm@10.21.0", | ||
| "packageManager": "pnpm@10.28.0", | ||
| "engines": { | ||
| "node": "^20.19.0 || >=22.12.0" | ||
| }, | ||
| "compatiblePackages": { | ||
| "schemaVersion": 1, | ||
| "vite": { | ||
| "type": "compatible", | ||
| "versions": "^7 || ^8 || >=8.0.0-0" | ||
| }, | ||
| "rollup": { | ||
| "type": "compatible", | ||
| "versions": "^4" | ||
| }, | ||
| "rolldown": { | ||
| "type": "compatible", | ||
| "versions": ">=1.0.0-beta.0" | ||
| } | ||
| } | ||
| } |
+2
-0
@@ -0,1 +1,3 @@ | ||
| [](https://deepwiki.com/nitrojs/nitro) | ||
| # Nitro | ||
@@ -2,0 +4,0 @@ |
| import { i as __toESM } from "../_chunks/Bqks5huO.mjs"; | ||
| import { O as relative, k as resolve, w as join, x as dirname } from "../_libs/c12.mjs"; | ||
| import { i as unplugin } from "../_libs/unimport.mjs"; | ||
| import { t as glob } from "../_libs/tinyglobby.mjs"; | ||
| import { t as src_default } from "../_libs/mime.mjs"; | ||
| import { i as genSafeVariableName, t as genImport } from "../_libs/knitwork.mjs"; | ||
| import { t as unwasm } from "../_libs/unwasm.mjs"; | ||
| import { t as replace } from "../_libs/plugin-replace.mjs"; | ||
| import { t as require_etag } from "../_libs/etag.mjs"; | ||
| import { camelCase } from "scule"; | ||
| import { promises } from "node:fs"; | ||
| import { joinURL, withTrailingSlash } from "ufo"; | ||
| import { readFile } from "node:fs/promises"; | ||
| import { defu } from "defu"; | ||
| import { pkgDir, runtimeDependencies, runtimeDir } from "nitro/meta"; | ||
| import { hash } from "ohash"; | ||
| import { defineEnv } from "unenv"; | ||
| import { connectors } from "db0"; | ||
| import { transform } from "oxc-transform"; | ||
| import { builtinDrivers, normalizeKey } from "unstorage"; | ||
| import { rollupNodeFileTrace } from "nf3"; | ||
| import { RENDER_CONTEXT_KEYS, compileTemplateToString, hasTemplateSyntax } from "rendu"; | ||
| //#region src/build/config.ts | ||
| function baseBuildConfig(nitro) { | ||
| const presetsDir$1 = resolve(runtimeDir, "../presets"); | ||
| const extensions = [ | ||
| ".ts", | ||
| ".mjs", | ||
| ".js", | ||
| ".json", | ||
| ".node", | ||
| ".tsx", | ||
| ".jsx" | ||
| ]; | ||
| const isNodeless = nitro.options.node === false; | ||
| const importMetaInjections = { | ||
| dev: nitro.options.dev, | ||
| preset: nitro.options.preset, | ||
| prerender: nitro.options.preset === "nitro-prerender", | ||
| nitro: true, | ||
| server: true, | ||
| client: false, | ||
| baseURL: nitro.options.baseURL, | ||
| _asyncContext: nitro.options.experimental.asyncContext, | ||
| _tasks: nitro.options.experimental.tasks | ||
| }; | ||
| const replacements = { | ||
| ...Object.fromEntries(Object.entries(importMetaInjections).map(([key, val]) => [`import.meta.${key}`, JSON.stringify(val)])), | ||
| ...nitro.options.replace | ||
| }; | ||
| const noExternal = [ | ||
| "#", | ||
| "~", | ||
| "@/", | ||
| "~~", | ||
| "@@/", | ||
| "virtual:", | ||
| "nitro", | ||
| pkgDir, | ||
| nitro.options.serverDir, | ||
| nitro.options.buildDir, | ||
| dirname(nitro.options.entry), | ||
| ...nitro.options.experimental.wasm ? [(id) => id?.endsWith(".wasm")] : [], | ||
| ...nitro.options.handlers.map((m) => m.handler).filter((i) => typeof i === "string"), | ||
| ...nitro.options.dev || nitro.options.preset === "nitro-prerender" ? [] : runtimeDependencies | ||
| ].filter(Boolean); | ||
| const { env } = defineEnv({ | ||
| nodeCompat: isNodeless, | ||
| resolve: true, | ||
| presets: nitro.options.unenv, | ||
| overrides: { alias: nitro.options.alias } | ||
| }); | ||
| return { | ||
| presetsDir: presetsDir$1, | ||
| extensions, | ||
| isNodeless, | ||
| replacements, | ||
| env, | ||
| aliases: resolveAliases({ ...env.alias }), | ||
| noExternal | ||
| }; | ||
| } | ||
| function resolveAliases(_aliases) { | ||
| const aliases = Object.fromEntries(Object.entries(_aliases).sort(([a], [b]) => b.split("/").length - a.split("/").length || b.length - a.length)); | ||
| for (const key in aliases) for (const alias in aliases) { | ||
| if (![ | ||
| "~", | ||
| "@", | ||
| "#" | ||
| ].includes(alias[0])) continue; | ||
| if (alias === "@" && !aliases[key].startsWith("@/")) continue; | ||
| if (aliases[key].startsWith(alias)) aliases[key] = aliases[alias] + aliases[key].slice(alias.length); | ||
| } | ||
| return aliases; | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/virtual.ts | ||
| const PREFIX = "\0virtual:"; | ||
| function virtual(modules, cache = {}, opts) { | ||
| const _modules = /* @__PURE__ */ new Map(); | ||
| for (const [id, mod] of Object.entries(modules)) { | ||
| cache[id] = mod; | ||
| _modules.set(id, mod); | ||
| _modules.set(resolve(id), mod); | ||
| } | ||
| return { | ||
| name: "virtual", | ||
| resolveId(id, importer) { | ||
| if (id in modules) return { | ||
| id: PREFIX + id, | ||
| ...opts | ||
| }; | ||
| if (importer) { | ||
| const resolved = resolve(dirname(importer.startsWith(PREFIX) ? importer.slice(9) : importer), id); | ||
| if (_modules.has(resolved)) return PREFIX + resolved; | ||
| } | ||
| return null; | ||
| }, | ||
| async load(id) { | ||
| if (!id.startsWith(PREFIX)) return null; | ||
| const idNoPrefix = id.slice(9); | ||
| if (!_modules.has(idNoPrefix)) return null; | ||
| let m = _modules.get(idNoPrefix); | ||
| if (typeof m === "function") m = await m(); | ||
| if (!m) return null; | ||
| cache[id.replace(PREFIX, "")] = m; | ||
| return { | ||
| code: m, | ||
| map: null | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/database.ts | ||
| function database(nitro) { | ||
| if (!nitro.options.experimental.database) return virtual({ "#nitro-internal-virtual/database": () => { | ||
| return `export const connectionConfigs = {};`; | ||
| } }, nitro.vfs); | ||
| const dbConfigs = nitro.options.dev && nitro.options.devDatabase || nitro.options.database; | ||
| const connectorsNames = [...new Set(Object.values(dbConfigs || {}).map((config) => config?.connector))].filter(Boolean); | ||
| for (const name of connectorsNames) if (!connectors[name]) throw new Error(`Database connector "${name}" is invalid.`); | ||
| return virtual({ "#nitro-internal-virtual/database": () => { | ||
| return ` | ||
| ${connectorsNames.map((name) => `import ${camelCase(name)}Connector from "${connectors[name]}";`).join("\n")} | ||
| export const connectionConfigs = { | ||
| ${Object.entries(dbConfigs || {}).map(([name, { connector, options }]) => `${name}: { | ||
| connector: ${camelCase(connector)}Connector, | ||
| options: ${JSON.stringify(options)} | ||
| }`).join(",\n")} | ||
| }; | ||
| `; | ||
| } }, nitro.vfs); | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/routing.ts | ||
| const RuntimeRouteRules = [ | ||
| "headers", | ||
| "redirect", | ||
| "proxy", | ||
| "cache" | ||
| ]; | ||
| function routing(nitro) { | ||
| return virtual({ | ||
| "#nitro-internal-virtual/routing": () => { | ||
| const allHandlers = uniqueBy([ | ||
| ...Object.values(nitro.routing.routes.routes).flatMap((h) => h.data), | ||
| ...Object.values(nitro.routing.routedMiddleware.routes).map((h) => h.data), | ||
| ...nitro.routing.globalMiddleware | ||
| ], "_importHash"); | ||
| return ` | ||
| import * as __routeRules__ from "nitro/~internal/runtime/route-rules"; | ||
| import * as srvxNode from "srvx/node" | ||
| import * as h3 from "h3"; | ||
| export const findRouteRules = ${nitro.routing.routeRules.compileToString({ | ||
| serialize: serializeRouteRule, | ||
| matchAll: true | ||
| })} | ||
| const multiHandler = (...handlers) => { | ||
| const final = handlers.pop() | ||
| const middleware = handlers.filter(Boolean).map(h => h3.toMiddleware(h)); | ||
| return (ev) => h3.callMiddleware(ev, middleware, final); | ||
| } | ||
| ${allHandlers.filter((h) => !h.lazy).map((h) => `import ${h._importHash} from "${h.handler}";`).join("\n")} | ||
| ${allHandlers.filter((h) => h.lazy).map((h) => `const ${h._importHash} = h3.defineLazyEventHandler(() => import("${h.handler}")${h.format === "node" ? ".then(m => srvxNode.toFetchHandler(m.default))" : ""});`).join("\n")} | ||
| export const findRoute = ${nitro.routing.routes.compileToString({ serialize: serializeHandler })} | ||
| export const findRoutedMiddleware = ${nitro.routing.routedMiddleware.compileToString({ | ||
| serialize: serializeHandler, | ||
| matchAll: true | ||
| })}; | ||
| export const globalMiddleware = [ | ||
| ${nitro.routing.globalMiddleware.map((h) => h.lazy ? h._importHash : `h3.toEventHandler(${h._importHash})`).join(",")} | ||
| ].filter(Boolean); | ||
| `; | ||
| }, | ||
| "#nitro-internal-virtual/routing-meta": () => { | ||
| const routeHandlers = uniqueBy(Object.values(nitro.routing.routes.routes).flatMap((h) => h.data), "_importHash"); | ||
| return ` | ||
| ${routeHandlers.map((h) => `import ${h._importHash}Meta from "${h.handler}?meta";`).join("\n")} | ||
| export const handlersMeta = [ | ||
| ${routeHandlers.map((h) => `{ route: ${JSON.stringify(h.route)}, method: ${JSON.stringify(h.method?.toLowerCase())}, meta: ${h._importHash}Meta }`).join(",\n")} | ||
| ]; | ||
| `.trim(); | ||
| } | ||
| }, nitro.vfs); | ||
| } | ||
| function uniqueBy(arr, key) { | ||
| return [...new Map(arr.map((item) => [item[key], item])).values()]; | ||
| } | ||
| function serializeHandler(h) { | ||
| const meta = Array.isArray(h) ? h[0] : h; | ||
| return `{${[ | ||
| `route:${JSON.stringify(meta.route)}`, | ||
| meta.method && `method:${JSON.stringify(meta.method)}`, | ||
| meta.meta && `meta:${JSON.stringify(meta.meta)}`, | ||
| `handler:${Array.isArray(h) ? `multiHandler(${h.map((handler) => serializeHandlerFn(handler)).join(",")})` : serializeHandlerFn(h)}` | ||
| ].filter(Boolean).join(",")}}`; | ||
| } | ||
| function serializeHandlerFn(h) { | ||
| let code = h._importHash; | ||
| if (!h.lazy) { | ||
| if (h.format === "node") code = `srvxNode.toFetchHandler(${code})`; | ||
| code = `h3.toEventHandler(${code})`; | ||
| } | ||
| return code; | ||
| } | ||
| function serializeRouteRule(h) { | ||
| return `[${Object.entries(h).filter(([name, options]) => options !== void 0 && name[0] !== "_").map(([name, options]) => { | ||
| return `{${[ | ||
| `name:${JSON.stringify(name)}`, | ||
| `route:${JSON.stringify(h._route)}`, | ||
| h._method && `method:${JSON.stringify(h._method)}`, | ||
| RuntimeRouteRules.includes(name) && `handler:__routeRules__.${name}`, | ||
| `options:${JSON.stringify(options)}` | ||
| ].filter(Boolean).join(",")}}`; | ||
| }).join(",")}]`; | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/route-meta.ts | ||
| const virtualPrefix = "\0nitro-handler-meta:"; | ||
| function routeMeta(nitro) { | ||
| return { | ||
| name: "nitro:route-meta", | ||
| async resolveId(id, importer, resolveOpts) { | ||
| if (id.startsWith("\0")) return; | ||
| if (id.endsWith(`?meta`)) { | ||
| const resolved = await this.resolve(id.replace(`?meta`, ``), importer, resolveOpts); | ||
| if (!resolved) return; | ||
| return virtualPrefix + resolved.id; | ||
| } | ||
| }, | ||
| load(id) { | ||
| if (id.startsWith(virtualPrefix)) return readFile(id.slice(20), { encoding: "utf8" }); | ||
| }, | ||
| async transform(code, id) { | ||
| if (!id.startsWith(virtualPrefix)) return; | ||
| let meta = null; | ||
| try { | ||
| const jsCode = transform(id, code).code; | ||
| const ast = this.parse(jsCode); | ||
| for (const node of ast.body) if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && node.expression.callee.type === "Identifier" && node.expression.callee.name === "defineRouteMeta" && node.expression.arguments.length === 1) { | ||
| meta = astToObject(node.expression.arguments[0]); | ||
| break; | ||
| } | ||
| } catch (error) { | ||
| nitro.logger.warn(`[handlers-meta] Cannot extra route meta for: ${id}: ${error}`); | ||
| } | ||
| return { | ||
| code: `export default ${JSON.stringify(meta)};`, | ||
| map: null | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| function astToObject(node) { | ||
| switch (node.type) { | ||
| case "ObjectExpression": { | ||
| const obj = {}; | ||
| for (const prop of node.properties) if (prop.type === "Property") { | ||
| const key = prop.key.name ?? prop.key.value; | ||
| obj[key] = astToObject(prop.value); | ||
| } | ||
| return obj; | ||
| } | ||
| case "ArrayExpression": return node.elements.map((el) => astToObject(el)).filter(Boolean); | ||
| case "Literal": return node.value; | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/server-main.ts | ||
| function serverMain(nitro) { | ||
| return { | ||
| name: "nitro:server-main", | ||
| renderChunk(code, chunk) { | ||
| if (chunk.isEntry) return { | ||
| code: `globalThis.__nitro_main__ = import.meta.url; ${code}`, | ||
| map: null | ||
| }; | ||
| } | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/public-assets.ts | ||
| var import_etag$1 = /* @__PURE__ */ __toESM(require_etag(), 1); | ||
| const readAssetHandler = { | ||
| true: "node", | ||
| node: "node", | ||
| false: "null", | ||
| deno: "deno", | ||
| inline: "inline" | ||
| }; | ||
| function publicAssets(nitro) { | ||
| return virtual({ | ||
| "#nitro-internal-virtual/public-assets-data": async () => { | ||
| const assets = {}; | ||
| const files = await glob("**", { | ||
| cwd: nitro.options.output.publicDir, | ||
| absolute: false, | ||
| dot: true | ||
| }); | ||
| for (const id of files) { | ||
| let mimeType = src_default.getType(id.replace(/\.(gz|br)$/, "")) || "text/plain"; | ||
| if (mimeType.startsWith("text")) mimeType += "; charset=utf-8"; | ||
| const fullPath = resolve(nitro.options.output.publicDir, id); | ||
| const assetData = await promises.readFile(fullPath); | ||
| const etag = (0, import_etag$1.default)(assetData); | ||
| const stat$1 = await promises.stat(fullPath); | ||
| const assetId = joinURL(nitro.options.baseURL, decodeURIComponent(id)); | ||
| let encoding; | ||
| if (id.endsWith(".gz")) encoding = "gzip"; | ||
| else if (id.endsWith(".br")) encoding = "br"; | ||
| assets[assetId] = { | ||
| type: nitro._prerenderMeta?.[assetId]?.contentType || mimeType, | ||
| encoding, | ||
| etag, | ||
| mtime: stat$1.mtime.toJSON(), | ||
| size: stat$1.size, | ||
| path: relative(nitro.options.output.serverDir, fullPath), | ||
| data: nitro.options.serveStatic === "inline" ? assetData.toString("base64") : void 0 | ||
| }; | ||
| } | ||
| return `export default ${JSON.stringify(assets, null, 2)};`; | ||
| }, | ||
| "#nitro-internal-virtual/public-assets-node": () => { | ||
| return ` | ||
| import { promises as fsp } from 'node:fs' | ||
| import { fileURLToPath } from 'node:url' | ||
| import { resolve, dirname } from 'node:path' | ||
| import assets from '#nitro-internal-virtual/public-assets-data' | ||
| export function readAsset (id) { | ||
| const serverDir = dirname(fileURLToPath(globalThis.__nitro_main__)) | ||
| return fsp.readFile(resolve(serverDir, assets[id].path)) | ||
| }`; | ||
| }, | ||
| "#nitro-internal-virtual/public-assets-deno": () => { | ||
| return ` | ||
| import assets from '#nitro-internal-virtual/public-assets-data' | ||
| export function readAsset (id) { | ||
| // https://deno.com/deploy/docs/serve-static-assets | ||
| const path = '.' + decodeURIComponent(new URL(\`../public\${id}\`, 'file://').pathname) | ||
| return Deno.readFile(path); | ||
| }`; | ||
| }, | ||
| "#nitro-internal-virtual/public-assets-null": () => { | ||
| return ` | ||
| export function readAsset (id) { | ||
| return Promise.resolve(null); | ||
| }`; | ||
| }, | ||
| "#nitro-internal-virtual/public-assets-inline": () => { | ||
| return ` | ||
| import assets from '#nitro-internal-virtual/public-assets-data' | ||
| export function readAsset (id) { | ||
| if (!assets[id]) { return undefined } | ||
| if (assets[id]._data) { return assets[id]._data } | ||
| if (!assets[id].data) { return assets[id].data } | ||
| assets[id]._data = Uint8Array.from(atob(assets[id].data), (c) => c.charCodeAt(0)) | ||
| return assets[id]._data | ||
| }`; | ||
| }, | ||
| "#nitro-internal-virtual/public-assets": () => { | ||
| const publicAssetBases = Object.fromEntries(nitro.options.publicAssets.filter((dir) => !dir.fallthrough && dir.baseURL !== "/").map((dir) => [withTrailingSlash(joinURL(nitro.options.baseURL, dir.baseURL || "/")), { maxAge: dir.maxAge }])); | ||
| return ` | ||
| import assets from '#nitro-internal-virtual/public-assets-data' | ||
| export { readAsset } from "${`#nitro-internal-virtual/public-assets-${readAssetHandler[nitro.options.serveStatic] || "null"}`}" | ||
| export const publicAssetBases = ${JSON.stringify(publicAssetBases)} | ||
| export function isPublicAssetURL(id = '') { | ||
| if (assets[id]) { | ||
| return true | ||
| } | ||
| for (const base in publicAssetBases) { | ||
| if (id.startsWith(base)) { return true } | ||
| } | ||
| return false | ||
| } | ||
| export function getPublicAssetMeta(id = '') { | ||
| for (const base in publicAssetBases) { | ||
| if (id.startsWith(base)) { return publicAssetBases[base] } | ||
| } | ||
| return {} | ||
| } | ||
| export function getAsset (id) { | ||
| return assets[id] | ||
| } | ||
| `; | ||
| } | ||
| }, nitro.vfs); | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/server-assets.ts | ||
| var import_etag = /* @__PURE__ */ __toESM(require_etag(), 1); | ||
| function serverAssets(nitro) { | ||
| if (nitro.options.dev || nitro.options.preset === "nitro-prerender") return virtual({ "#nitro-internal-virtual/server-assets": getAssetsDev(nitro) }, nitro.vfs); | ||
| return virtual({ "#nitro-internal-virtual/server-assets": async () => { | ||
| const assets = {}; | ||
| for (const asset of nitro.options.serverAssets) { | ||
| const files = await glob(asset.pattern || "**/*", { | ||
| cwd: asset.dir, | ||
| absolute: false, | ||
| ignore: asset.ignore | ||
| }); | ||
| for (const _id of files) { | ||
| const fsPath = resolve(asset.dir, _id); | ||
| const id = asset.baseName + "/" + _id; | ||
| assets[id] = { | ||
| fsPath, | ||
| meta: {} | ||
| }; | ||
| let type = src_default.getType(id) || "text/plain"; | ||
| if (type.startsWith("text")) type += "; charset=utf-8"; | ||
| const etag = (0, import_etag.default)(await promises.readFile(fsPath)); | ||
| const mtime = await promises.stat(fsPath).then((s) => s.mtime.toJSON()); | ||
| assets[id].meta = { | ||
| type, | ||
| etag, | ||
| mtime | ||
| }; | ||
| } | ||
| } | ||
| return getAssetProd(assets); | ||
| } }, nitro.vfs); | ||
| } | ||
| function getAssetsDev(nitro) { | ||
| return ` | ||
| import { createStorage } from 'unstorage' | ||
| import fsDriver from 'unstorage/drivers/fs' | ||
| const serverAssets = ${JSON.stringify(nitro.options.serverAssets)} | ||
| export const assets = createStorage() | ||
| for (const asset of serverAssets) { | ||
| assets.mount(asset.baseName, fsDriver({ base: asset.dir, ignore: (asset?.ignore || []) })) | ||
| }`; | ||
| } | ||
| function getAssetProd(assets) { | ||
| return ` | ||
| const _assets = {\n${Object.entries(assets).map(([id, asset]) => ` [${JSON.stringify(normalizeKey(id))}]: {\n import: () => import(${JSON.stringify("raw:" + asset.fsPath)}).then(r => r.default || r),\n meta: ${JSON.stringify(asset.meta)}\n }`).join(",\n")}\n} | ||
| const normalizeKey = ${normalizeKey.toString()} | ||
| export const assets = { | ||
| 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 : {}) | ||
| } | ||
| } | ||
| `; | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/storage.ts | ||
| function storage(nitro) { | ||
| const mounts = []; | ||
| const storageMounts = nitro.options.dev || nitro.options.preset === "nitro-prerender" ? { | ||
| ...nitro.options.storage, | ||
| ...nitro.options.devStorage | ||
| } : nitro.options.storage; | ||
| for (const path in storageMounts) { | ||
| const mount = storageMounts[path]; | ||
| mounts.push({ | ||
| path, | ||
| driver: builtinDrivers[mount.driver] || mount.driver, | ||
| opts: mount | ||
| }); | ||
| } | ||
| const driverImports = [...new Set(mounts.map((m) => m.driver))]; | ||
| return virtual({ "#nitro-internal-virtual/storage": ` | ||
| import { createStorage } from 'unstorage' | ||
| import { assets } from '#nitro-internal-virtual/server-assets' | ||
| ${driverImports.map((i) => genImport(i, genSafeVariableName(i))).join("\n")} | ||
| export function initStorage() { | ||
| const storage = createStorage({}) | ||
| storage.mount('/assets', assets) | ||
| ${mounts.map((m) => `storage.mount('${m.path}', ${genSafeVariableName(m.driver)}(${JSON.stringify(m.opts)}))`).join("\n")} | ||
| return storage | ||
| } | ||
| ` }, nitro.vfs); | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/error-handler.ts | ||
| function errorHandler(nitro) { | ||
| return virtual({ "#nitro-internal-virtual/error-handler": () => { | ||
| const errorHandlers = Array.isArray(nitro.options.errorHandler) ? nitro.options.errorHandler : [nitro.options.errorHandler]; | ||
| const builtinHandler = join(runtimeDir, `internal/error/${nitro.options.dev ? "dev" : "prod"}`); | ||
| return ` | ||
| ${errorHandlers.map((h, i) => `import errorHandler$${i} from "${h}";`).join("\n")} | ||
| const errorHandlers = [${errorHandlers.map((_, i) => `errorHandler$${i}`).join(", ")}]; | ||
| import { defaultHandler } from "${builtinHandler}"; | ||
| export default async function(error, event) { | ||
| for (const handler of errorHandlers) { | ||
| try { | ||
| const response = await handler(error, event, { defaultHandler }); | ||
| if (response) { | ||
| return response; | ||
| } | ||
| } catch(error) { | ||
| // Handler itself thrown, log and continue | ||
| console.error(error); | ||
| } | ||
| } | ||
| // H3 will handle fallback | ||
| } | ||
| `; | ||
| } }, nitro.vfs); | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/renderer-template.ts | ||
| function rendererTemplate(nitro) { | ||
| return virtual({ "#nitro-internal-virtual/renderer-template": async () => { | ||
| const template = nitro.options.renderer?.template; | ||
| if (typeof template !== "string") return ` | ||
| export const rendererTemplate = () => '<!-- renderer.template is not set -->'; | ||
| export const rendererTemplateFile = undefined; | ||
| export const isStaticTemplate = true;`; | ||
| if (nitro.options.dev) return ` | ||
| import { readFile } from 'node:fs/promises'; | ||
| export const rendererTemplate = () => readFile(${JSON.stringify(template)}, "utf8"); | ||
| export const rendererTemplateFile = ${JSON.stringify(template)}; | ||
| export const isStaticTemplate = ${JSON.stringify(nitro.options.renderer?.static)}; | ||
| `; | ||
| else { | ||
| const html = await readFile(template, "utf8"); | ||
| if (nitro.options.renderer?.static ?? !hasTemplateSyntax(html)) return ` | ||
| import { HTTPResponse } from "h3"; | ||
| export const rendererTemplate = () => new HTTPResponse(${JSON.stringify(html)}, { headers: { "content-type": "text/html; charset=utf-8" } }); | ||
| `; | ||
| else return ` | ||
| import { renderToResponse } from 'rendu' | ||
| import { serverFetch } from 'nitro/app' | ||
| const template = ${compileTemplateToString(html, { contextKeys: [...RENDER_CONTEXT_KEYS] })}; | ||
| export const rendererTemplate = (request) => renderToResponse(template, { request, context: { serverFetch } }) | ||
| `; | ||
| } | ||
| } }, nitro.vfs); | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/feature-flags.ts | ||
| function featureFlags(nitro) { | ||
| return virtual({ "#nitro-internal-virtual/feature-flags": () => { | ||
| const featureFlags$1 = { | ||
| hasRoutes: nitro.routing.routes.hasRoutes(), | ||
| hasRouteRules: nitro.routing.routeRules.hasRoutes(), | ||
| hasRoutedMiddleware: nitro.routing.routedMiddleware.hasRoutes(), | ||
| hasGlobalMiddleware: nitro.routing.globalMiddleware.length > 0, | ||
| hasPlugins: nitro.options.plugins.length > 0, | ||
| hasHooks: nitro.options.features?.runtimeHooks ?? nitro.options.plugins.length > 0, | ||
| hasWebSocket: nitro.options.features?.websocket ?? nitro.options.experimental.websocket ?? false | ||
| }; | ||
| return Object.entries(featureFlags$1).map(([key, value]) => `export const ${key} = ${Boolean(value)};`).join("\n"); | ||
| } }, nitro.vfs); | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/resolve.ts | ||
| const subpathMap = { | ||
| "nitro/h3": "h3", | ||
| "nitro/deps/h3": "h3", | ||
| "nitro/deps/ofetch": "ofetch" | ||
| }; | ||
| function nitroResolveIds() { | ||
| return { | ||
| name: "nitro:resolve-ids", | ||
| resolveId: { | ||
| order: "pre", | ||
| handler(id, importer, rOpts) { | ||
| if (importer && importer.startsWith("\0virtual:#nitro-internal-virtual")) return this.resolve(id, runtimeDir, { skipSelf: true }); | ||
| const mappedId = subpathMap[id]; | ||
| if (mappedId) return this.resolve(mappedId, runtimeDir, { skipSelf: true }); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/sourcemap-min.ts | ||
| function sourcemapMinify() { | ||
| return { | ||
| name: "nitro:sourcemap-minify", | ||
| generateBundle(_options, bundle) { | ||
| for (const [key, asset] of Object.entries(bundle)) { | ||
| if (!key.endsWith(".map") || !("source" in asset) || typeof asset.source !== "string") continue; | ||
| const sourcemap = JSON.parse(asset.source); | ||
| delete sourcemap.sourcesContent; | ||
| delete sourcemap.x_google_ignoreList; | ||
| if ((sourcemap.sources || []).some((s) => s.includes("node_modules"))) sourcemap.mappings = ""; | ||
| asset.source = JSON.stringify(sourcemap); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/raw.ts | ||
| const HELPER_ID = "virtual:raw-helpers"; | ||
| const RESOLVED_RAW_PREFIX = "virtual:raw:"; | ||
| function raw() { | ||
| return { | ||
| name: "raw", | ||
| resolveId: { | ||
| order: "pre", | ||
| async handler(id, importer, resolveOpts) { | ||
| if (id === HELPER_ID) return id; | ||
| if (id.startsWith("raw:")) return { id: RESOLVED_RAW_PREFIX + (await this.resolve(id.slice(4), importer, resolveOpts))?.id }; | ||
| } | ||
| }, | ||
| load: { | ||
| order: "pre", | ||
| handler(id) { | ||
| if (id === HELPER_ID) return getHelpers(); | ||
| if (id.startsWith(RESOLVED_RAW_PREFIX)) return promises.readFile(id.slice(12), isBinary(id) ? "binary" : "utf8"); | ||
| } | ||
| }, | ||
| transform: { | ||
| order: "pre", | ||
| handler(code, id) { | ||
| if (!id.startsWith(RESOLVED_RAW_PREFIX)) return; | ||
| if (isBinary(id)) return { | ||
| code: `import {base64ToUint8Array } from "${HELPER_ID}" \n export default base64ToUint8Array("${Buffer.from(code, "binary").toString("base64")}")`, | ||
| map: null | ||
| }; | ||
| return { | ||
| code: `export default ${JSON.stringify(code)}`, | ||
| map: null, | ||
| moduleType: "js" | ||
| }; | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function isBinary(id) { | ||
| const idMime = src_default.getType(id) || ""; | ||
| if (idMime.startsWith("text/")) return false; | ||
| if (/application\/(json|sql|xml|yaml)/.test(idMime)) return false; | ||
| return true; | ||
| } | ||
| function getHelpers() { | ||
| return String.raw` | ||
| export function base64ToUint8Array(str) { | ||
| const data = atob(str); | ||
| const size = data.length; | ||
| const bytes = new Uint8Array(size); | ||
| for (let i = 0; i < size; i++) { | ||
| bytes[i] = data.charCodeAt(i); | ||
| } | ||
| return bytes; | ||
| } | ||
| `; | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins/runtime-config.ts | ||
| function runtimeConfig(nitro) { | ||
| return virtual({ "#nitro-internal-virtual/runtime-config": () => { | ||
| return `export const runtimeConfig = ${JSON.stringify(nitro.options.runtimeConfig || {})};`; | ||
| } }, nitro.vfs); | ||
| } | ||
| //#endregion | ||
| //#region src/build/plugins.ts | ||
| function baseBuildPlugins(nitro, base) { | ||
| const plugins = []; | ||
| if (nitro.options.imports) plugins.push(unplugin.rollup(nitro.options.imports)); | ||
| if (nitro.options.experimental.wasm) plugins.push(unwasm(nitro.options.wasm || {})); | ||
| plugins.push(serverMain(nitro)); | ||
| const nitroPlugins = [...new Set(nitro.options.plugins)]; | ||
| plugins.push(virtual({ "#nitro-internal-virtual/plugins": ` | ||
| ${nitroPlugins.map((plugin) => `import _${hash(plugin).replace(/-/g, "")} from '${plugin}';`).join("\n")} | ||
| export const plugins = [ | ||
| ${nitroPlugins.map((plugin) => `_${hash(plugin).replace(/-/g, "")}`).join(",\n")} | ||
| ] | ||
| ` }, nitro.vfs)); | ||
| plugins.push(featureFlags(nitro)); | ||
| plugins.push(nitroResolveIds()); | ||
| plugins.push(serverAssets(nitro)); | ||
| plugins.push(publicAssets(nitro)); | ||
| plugins.push(storage(nitro)); | ||
| plugins.push(database(nitro)); | ||
| plugins.push(routing(nitro)); | ||
| plugins.push(raw()); | ||
| if (nitro.options.experimental.openAPI) plugins.push(routeMeta(nitro)); | ||
| plugins.push(runtimeConfig(nitro)); | ||
| plugins.push(errorHandler(nitro)); | ||
| plugins.push(virtual({ "#nitro-internal-pollyfills": base.env.polyfill.map((p) => `import '${p}';`).join("\n") || `/* No polyfills */` }, nitro.vfs, { moduleSideEffects: true })); | ||
| plugins.push(virtual(nitro.options.virtual, nitro.vfs)); | ||
| if (nitro.options.renderer?.template) plugins.push(rendererTemplate(nitro)); | ||
| plugins.push(replace({ | ||
| preventAssignment: true, | ||
| values: base.replacements | ||
| })); | ||
| if (!nitro.options.noExternals) plugins.push(rollupNodeFileTrace(defu(nitro.options.externals, { | ||
| outDir: nitro.options.output.serverDir, | ||
| moduleDirectories: nitro.options.nodeModulesDirs, | ||
| external: nitro.options.nodeModulesDirs, | ||
| inline: [...base.noExternal], | ||
| traceOptions: { | ||
| base: "/", | ||
| processCwd: nitro.options.rootDir, | ||
| exportsOnly: true | ||
| }, | ||
| traceAlias: { | ||
| "h3-nightly": "h3", | ||
| ...nitro.options.externals?.traceAlias | ||
| }, | ||
| exportConditions: nitro.options.exportConditions, | ||
| writePackageJson: true | ||
| }))); | ||
| if (nitro.options.sourcemap && !nitro.options.dev && nitro.options.experimental.sourcemapMinify !== false) plugins.push(sourcemapMinify()); | ||
| return plugins; | ||
| } | ||
| //#endregion | ||
| export { baseBuildConfig as n, baseBuildPlugins as t }; |
| import { C as isAbsolute$1, O as relative$1, T as normalize$1, b as basename$1, h as resolveModulePath, k as resolve$1, n as debounce, w as join$1, x as dirname$1 } from "../_libs/c12.mjs"; | ||
| import { f as sanitizeFilePath } from "../_libs/local-pkg.mjs"; | ||
| import { t as formatCompatibilityDate } from "../_libs/compatx.mjs"; | ||
| import { n as T, r as a } from "../_libs/std-env.mjs"; | ||
| import { a as createNitro, n as prepare, r as copyPublicAssets } from "../_chunks/B-D1JOIz.mjs"; | ||
| import { n as prettyPath } from "../_chunks/C7CbzoI1.mjs"; | ||
| import { i as scanHandlers } from "../_chunks/ANM1K1bE.mjs"; | ||
| import { n as writeBuildInfo, t as getBuildInfo } from "./common.mjs"; | ||
| import { i as NodeDevWorker, r as NitroDevApp } from "../_dev.mjs"; | ||
| import { i as watch$1 } from "../_libs/chokidar.mjs"; | ||
| import { t as alias } from "../_libs/plugin-alias.mjs"; | ||
| import { t as inject } from "../_libs/plugin-inject.mjs"; | ||
| import { n as baseBuildConfig, t as baseBuildPlugins } from "./common2.mjs"; | ||
| import { t as assetsPlugin } from "../_libs/vite-plugin-fullstack.mjs"; | ||
| import consola$1 from "consola"; | ||
| import { join, resolve } from "node:path"; | ||
| import { existsSync, watch } from "node:fs"; | ||
| import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; | ||
| import { defu } from "defu"; | ||
| import { runtimeDependencies, runtimeDir } from "nitro/meta"; | ||
| import { colors } from "consola/utils"; | ||
| import { NodeRequest, sendNodeResponse } from "srvx/node"; | ||
| import { DevEnvironment } from "vite"; | ||
| import { spawn } from "node:child_process"; | ||
| //#region src/build/vite/rollup.ts | ||
| /** | ||
| * Removed from base rollup config: | ||
| * - nodeResolve | ||
| * - commonjs | ||
| * - esbuild | ||
| * - sourcemapMinify | ||
| * - json | ||
| * - raw | ||
| * | ||
| * TODO: Reuse with rollup: | ||
| * - chunkFileNames | ||
| * - moduleSideEffects | ||
| */ | ||
| const getViteRollupConfig = (ctx) => { | ||
| const nitro$1 = ctx.nitro; | ||
| const base = baseBuildConfig(nitro$1); | ||
| const chunkNamePrefixes = [ | ||
| [runtimeDir, "nitro"], | ||
| [base.presetsDir, "nitro"], | ||
| ["\0nitro-wasm:", "wasm"], | ||
| ["\0", "virtual"] | ||
| ]; | ||
| function getChunkGroup(id) { | ||
| if (id.startsWith(runtimeDir) || id.startsWith(base.presetsDir)) return "nitro"; | ||
| } | ||
| let config = { | ||
| input: nitro$1.options.entry, | ||
| external: [...base.env.external], | ||
| plugins: [ | ||
| ctx.pluginConfig.experimental?.vite?.virtualBundle && virtualBundlePlugin(ctx._serviceBundles), | ||
| ...baseBuildPlugins(nitro$1, base), | ||
| alias({ entries: base.aliases }), | ||
| !ctx._isRolldown && inject(base.env.inject) | ||
| ].filter(Boolean), | ||
| ...ctx._isRolldown ? { transform: { inject: base.env.inject } } : {}, | ||
| treeshake: { moduleSideEffects(id) { | ||
| return nitro$1.options.moduleSideEffects.some((p) => id.startsWith(p)); | ||
| } }, | ||
| output: { | ||
| dir: nitro$1.options.output.serverDir, | ||
| entryFileNames: "index.mjs", | ||
| chunkFileNames(chunk) { | ||
| const id = normalize$1(chunk.moduleIds.at(-1) || ""); | ||
| for (const [dir, name] of chunkNamePrefixes) if (id.startsWith(dir)) return `chunks/${name}/[name].mjs`; | ||
| const routeHandler = nitro$1.options.handlers.find((h) => id.startsWith(h.handler)) || nitro$1.scannedHandlers.find((h) => id.startsWith(h.handler)); | ||
| if (routeHandler?.route) return `chunks/routes/${routeHandler.route.replace(/:([^/]+)/g, "_$1").replace(/\/[^/]+$/g, "").replace(/[^a-zA-Z0-9/_-]/g, "_") || "/"}/[name].mjs`.replace(/\/+/g, "/"); | ||
| if (Object.entries(nitro$1.options.tasks).find(([_, task]) => task.handler === id)) return `chunks/tasks/[name].mjs`; | ||
| return `chunks/_/[name].mjs`; | ||
| }, | ||
| manualChunks(id) { | ||
| return getChunkGroup(id); | ||
| }, | ||
| inlineDynamicImports: nitro$1.options.inlineDynamicImports, | ||
| format: "esm", | ||
| exports: "auto", | ||
| intro: "", | ||
| outro: "", | ||
| generatedCode: { ...ctx._isRolldown ? {} : { constBindings: true } }, | ||
| sanitizeFileName: sanitizeFilePath, | ||
| ...ctx._isRolldown ? {} : { sourcemapExcludeSources: true }, | ||
| sourcemapIgnoreList(relativePath) { | ||
| return relativePath.includes("node_modules"); | ||
| } | ||
| } | ||
| }; | ||
| config = defu(nitro$1.options.rollupConfig, config); | ||
| if (config.output.inlineDynamicImports) delete config.output.manualChunks; | ||
| return { | ||
| config, | ||
| base | ||
| }; | ||
| }; | ||
| function virtualBundlePlugin(bundles) { | ||
| let _modules = null; | ||
| const getModules = () => { | ||
| if (_modules) return _modules; | ||
| _modules = /* @__PURE__ */ new Map(); | ||
| for (const bundle of Object.values(bundles)) for (const [fileName, content] of Object.entries(bundle)) if (content.type === "chunk") { | ||
| const virtualModule = { | ||
| code: content.code, | ||
| map: null | ||
| }; | ||
| const maybeMap = bundle[`${fileName}.map`]; | ||
| if (maybeMap && maybeMap.type === "asset") virtualModule.map = maybeMap.source; | ||
| _modules.set(fileName, virtualModule); | ||
| _modules.set(resolve$1(fileName), virtualModule); | ||
| } | ||
| return _modules; | ||
| }; | ||
| return { | ||
| name: "virtual-bundle", | ||
| resolveId(id, importer) { | ||
| const modules = getModules(); | ||
| if (modules.has(id)) return resolve$1(id); | ||
| if (importer) { | ||
| const resolved = resolve$1(dirname$1(importer), id); | ||
| if (modules.has(resolved)) return resolved; | ||
| } | ||
| return null; | ||
| }, | ||
| load(id) { | ||
| const m = getModules().get(id); | ||
| if (!m) return null; | ||
| return m; | ||
| } | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/build/vite/prod.ts | ||
| const BuilderNames = { | ||
| nitro: colors.magenta("Nitro"), | ||
| client: colors.green("Client"), | ||
| ssr: colors.blue("SSR") | ||
| }; | ||
| async function buildEnvironments(ctx, builder) { | ||
| const nitro$1 = ctx.nitro; | ||
| for (const [envName, env] of Object.entries(builder.environments)) { | ||
| const fmtName = BuilderNames[envName] || (envName.length <= 3 ? envName.toUpperCase() : envName[0].toUpperCase() + envName.slice(1)); | ||
| if (envName === "nitro" || !env.config.build.rollupOptions.input || env.isBuilt) { | ||
| if (![ | ||
| "nitro", | ||
| "ssr", | ||
| "client" | ||
| ].includes(envName)) nitro$1.logger.info(env.isBuilt ? `Skipping ${fmtName} (already built)` : `Skipping ${fmtName} (no input defined)`); | ||
| continue; | ||
| } | ||
| if (!a && !T) console.log(); | ||
| nitro$1.logger.start(`Building [${fmtName}]`); | ||
| await builder.build(env); | ||
| } | ||
| const nitroOptions = ctx.nitro.options; | ||
| const clientInput = builder.environments.client?.config?.build?.rollupOptions?.input; | ||
| if (nitroOptions.renderer?.template && nitroOptions.renderer?.template === clientInput) { | ||
| const outputPath = resolve$1(nitroOptions.output.publicDir, basename$1(clientInput)); | ||
| if (existsSync(outputPath)) { | ||
| const html = await readFile(outputPath, "utf8").then((r) => r.replace("<!--ssr-outlet-->", `{{{ globalThis.__nitro_vite_envs__?.["ssr"]?.fetch($REQUEST) || "" }}}`)); | ||
| await rm(outputPath); | ||
| const tmp = resolve$1(nitroOptions.buildDir, "vite/index.html"); | ||
| await mkdir(dirname$1(tmp), { recursive: true }); | ||
| await writeFile(tmp, html, "utf8"); | ||
| nitroOptions.renderer.template = tmp; | ||
| } | ||
| } | ||
| await builder.writeAssetsManifest?.(); | ||
| if (!a && !T) console.log(); | ||
| const buildInfo = [["preset", nitro$1.options.preset], ["compatibility", formatCompatibilityDate(nitro$1.options.compatibilityDate)]].filter((e) => e[1]); | ||
| nitro$1.logger.start(`Building [${BuilderNames.nitro}] ${colors.dim(`(${buildInfo.map(([k, v]) => `${k}: \`${v}\``).join(", ")})`)}`); | ||
| await copyPublicAssets(nitro$1); | ||
| const assetDirs = new Set(Object.values(builder.environments).filter((env) => env.config.consumer === "client").map((env) => env.config.build.assetsDir).filter(Boolean)); | ||
| for (const assetsDir of assetDirs) { | ||
| if (!existsSync(resolve$1(nitro$1.options.output.publicDir, assetsDir))) continue; | ||
| const rule = ctx.nitro.options.routeRules[`/${assetsDir}/**`] ??= {}; | ||
| if (!rule.headers?.["cache-control"]) rule.headers = { | ||
| ...rule.headers, | ||
| "cache-control": `public, max-age=31536000, immutable` | ||
| }; | ||
| } | ||
| ctx.nitro.routing.sync(); | ||
| await builder.build(builder.environments.nitro); | ||
| await nitro$1.close(); | ||
| await nitro$1.hooks.callHook("compiled", nitro$1); | ||
| await writeBuildInfo(nitro$1); | ||
| const rOutput = relative$1(process.cwd(), nitro$1.options.output.dir); | ||
| const rewriteRelativePaths = (input) => { | ||
| return input.replace(/([\s:])\.\/(\S*)/g, `$1${rOutput}/$2`); | ||
| }; | ||
| if (!a && !T) console.log(); | ||
| if (nitro$1.options.commands.preview) nitro$1.logger.success(`You can preview this build using \`${rewriteRelativePaths(nitro$1.options.commands.preview)}\``); | ||
| if (nitro$1.options.commands.deploy) nitro$1.logger.success(`You can deploy this build using \`${rewriteRelativePaths(nitro$1.options.commands.deploy)}\``); | ||
| } | ||
| function prodSetup(ctx) { | ||
| return ` | ||
| function lazyService(loader) { | ||
| let promise, mod | ||
| return { | ||
| fetch(req) { | ||
| if (mod) { return mod.fetch(req) } | ||
| if (!promise) { | ||
| promise = loader().then(_mod => (mod = _mod.default || _mod)) | ||
| } | ||
| return promise.then(mod => mod.fetch(req)) | ||
| } | ||
| } | ||
| } | ||
| const services = { | ||
| ${Object.keys(ctx.services).map((name) => { | ||
| let entry; | ||
| if (ctx.pluginConfig.experimental?.vite?.virtualBundle) entry = ctx._entryPoints[name]; | ||
| else entry = resolve$1(ctx.nitro.options.buildDir, "vite/services", name, ctx._entryPoints[name]); | ||
| return [name, entry]; | ||
| }).map(([name, entry]) => `[${JSON.stringify(name)}]: lazyService(() => import(${JSON.stringify(entry)}))`).join(",\n")} | ||
| }; | ||
| globalThis.__nitro_vite_envs__ = services; | ||
| `; | ||
| } | ||
| //#endregion | ||
| //#region src/build/vite/dev.ts | ||
| function createFetchableDevEnvironment(name, config, devServer, entry) { | ||
| return new FetchableDevEnvironment(name, config, { | ||
| hot: true, | ||
| transport: createTransport(name, devServer) | ||
| }, devServer, entry); | ||
| } | ||
| var FetchableDevEnvironment = class extends DevEnvironment { | ||
| devServer; | ||
| constructor(name, config, context, devServer, entry) { | ||
| super(name, config, context); | ||
| this.devServer = devServer; | ||
| this.devServer.sendMessage({ | ||
| type: "custom", | ||
| event: "nitro:vite-env", | ||
| data: { | ||
| name, | ||
| entry | ||
| } | ||
| }); | ||
| } | ||
| async dispatchFetch(request) { | ||
| return this.devServer.fetch(request); | ||
| } | ||
| async init(...args) { | ||
| await this.devServer.init?.(); | ||
| return super.init(...args); | ||
| } | ||
| }; | ||
| function createTransport(name, hooks) { | ||
| const listeners = /* @__PURE__ */ new WeakMap(); | ||
| return { | ||
| send: (data) => hooks.sendMessage({ | ||
| ...data, | ||
| viteEnv: name | ||
| }), | ||
| on: (event, handler) => { | ||
| if (event === "connection") return; | ||
| const listener = (value) => { | ||
| if (value?.type === "custom" && value.event === event && value.viteEnv === name) handler(value.data, { send: (payload) => hooks.sendMessage({ | ||
| ...payload, | ||
| viteEnv: name | ||
| }) }); | ||
| }; | ||
| listeners.set(handler, listener); | ||
| hooks.onMessage(listener); | ||
| }, | ||
| off: (event, handler) => { | ||
| if (event === "connection") return; | ||
| const listener = listeners.get(handler); | ||
| if (listener) { | ||
| hooks.offMessage(listener); | ||
| listeners.delete(handler); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| async function configureViteDevServer(ctx, server) { | ||
| const nitro$1 = ctx.nitro; | ||
| const nitroEnv$1 = server.environments.nitro; | ||
| const nitroConfigFile = nitro$1.options._c12.configFile; | ||
| if (nitroConfigFile) server.config.configFileDependencies.push(nitroConfigFile); | ||
| if (nitro$1.options.features.websocket ?? nitro$1.options.experimental.websocket) server.httpServer.on("upgrade", (req, socket, head) => { | ||
| if (req.url?.startsWith("/?token")) return; | ||
| ctx.devWorker?.upgrade(req, socket, head); | ||
| }); | ||
| const reload = debounce(async () => { | ||
| await scanHandlers(nitro$1); | ||
| nitro$1.routing.sync(); | ||
| nitroEnv$1.moduleGraph.invalidateAll(); | ||
| nitroEnv$1.hot.send({ type: "full-reload" }); | ||
| }); | ||
| const scanDirs = nitro$1.options.scanDirs.flatMap((dir) => [ | ||
| join$1(dir, nitro$1.options.apiDir || "api"), | ||
| join$1(dir, nitro$1.options.routesDir || "routes"), | ||
| join$1(dir, "middleware"), | ||
| join$1(dir, "plugins"), | ||
| join$1(dir, "modules") | ||
| ]); | ||
| const watchReloadEvents = new Set([ | ||
| "add", | ||
| "addDir", | ||
| "unlink", | ||
| "unlinkDir" | ||
| ]); | ||
| const scanDirsWatcher = watch$1(scanDirs, { ignoreInitial: true }).on("all", (event, path$1, stat$1) => { | ||
| if (watchReloadEvents.has(event)) reload(); | ||
| }); | ||
| const rootDirWatcher = watch(nitro$1.options.rootDir, { persistent: false }, (_event, filename) => { | ||
| if (filename && /^server\.[mc]?[jt]sx?$/.test(filename)) reload(); | ||
| }); | ||
| nitro$1.hooks.hook("close", () => { | ||
| scanDirsWatcher.close(); | ||
| rootDirWatcher.close(); | ||
| }); | ||
| const hostIPC = { async transformHTML(html) { | ||
| return server.transformIndexHtml("/", html).then((r) => r.replace("<!--ssr-outlet-->", `{{{ globalThis.__nitro_vite_envs__?.["ssr"]?.fetch($REQUEST) || "" }}}`)); | ||
| } }; | ||
| nitroEnv$1.devServer.onMessage(async (payload) => { | ||
| if (payload.type === "custom" && payload.event === "nitro:vite-invoke") { | ||
| const res = await hostIPC[payload.data.name](payload.data.data).then((data) => ({ data })).catch((error) => ({ error })); | ||
| nitroEnv$1.devServer.sendMessage({ | ||
| type: "custom", | ||
| event: "nitro:vite-invoke-response", | ||
| data: { | ||
| id: payload.data.id, | ||
| data: res | ||
| } | ||
| }); | ||
| } | ||
| }); | ||
| const nitroDevMiddleware = async (nodeReq, nodeRes, next) => { | ||
| if (/^\/@(?:vite|fs|id)\//.test(nodeReq.url) || nodeReq._nitroHandled) return next(); | ||
| nodeReq._nitroHandled = true; | ||
| const req = new NodeRequest({ | ||
| req: nodeReq, | ||
| res: nodeRes | ||
| }); | ||
| const devAppRes = await ctx.devApp.fetch(req); | ||
| if (nodeRes.writableEnded || nodeRes.headersSent) return; | ||
| if (devAppRes.status !== 404) return await sendNodeResponse(nodeRes, devAppRes); | ||
| const envRes = await nitroEnv$1.dispatchFetch(req); | ||
| if (nodeRes.writableEnded || nodeRes.headersSent) return; | ||
| if (envRes.status !== 404) return await sendNodeResponse(nodeRes, envRes); | ||
| return next(); | ||
| }; | ||
| server.middlewares.use(function nitroDevMiddlewarePre(req, res, next) { | ||
| const fetchDest = req.headers["sec-fetch-dest"]; | ||
| if (fetchDest) res.setHeader("vary", "sec-fetch-dest"); | ||
| if (!((req.url || "").match(/\.([a-z0-9]+)(?:[?#]|$)/i)?.[1] || "") && (!fetchDest || /^(document|iframe|frame|empty)$/.test(fetchDest))) nitroDevMiddleware(req, res, next); | ||
| else next(); | ||
| }); | ||
| return () => { | ||
| server.middlewares.use(nitroDevMiddleware); | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/build/vite/env.ts | ||
| function createDevWorker(ctx) { | ||
| return new NodeDevWorker({ | ||
| name: "nitro-vite", | ||
| entry: resolve(runtimeDir, "internal/vite/dev-worker.mjs"), | ||
| hooks: {}, | ||
| data: { | ||
| server: true, | ||
| globals: { __NITRO_RUNTIME_CONFIG__: ctx.nitro.options.runtimeConfig } | ||
| } | ||
| }); | ||
| } | ||
| function createNitroEnvironment(ctx) { | ||
| return { | ||
| consumer: "server", | ||
| build: { | ||
| rollupOptions: ctx.rollupConfig.config, | ||
| minify: ctx.nitro.options.minify, | ||
| emptyOutDir: false, | ||
| sourcemap: ctx.nitro.options.sourcemap, | ||
| commonjsOptions: { ...ctx.nitro.options.commonJS } | ||
| }, | ||
| resolve: { | ||
| noExternal: ctx.nitro.options.dev ? [...ctx.rollupConfig.base.noExternal, ...runtimeDependencies] : true, | ||
| conditions: ctx.nitro.options.exportConditions, | ||
| externalConditions: ctx.nitro.options.exportConditions | ||
| }, | ||
| dev: { createEnvironment: (envName, envConfig) => createFetchableDevEnvironment(envName, envConfig, ctx.devWorker, resolve(runtimeDir, "internal/vite/dev-entry.mjs")) } | ||
| }; | ||
| } | ||
| function createServiceEnvironment(ctx, name, serviceConfig) { | ||
| return { | ||
| consumer: "server", | ||
| build: { | ||
| rollupOptions: { input: serviceConfig.entry }, | ||
| minify: ctx.nitro.options.minify, | ||
| sourcemap: ctx.nitro.options.sourcemap, | ||
| outDir: join(ctx.nitro.options.buildDir, "vite/services", name), | ||
| emptyOutDir: true | ||
| }, | ||
| resolve: { | ||
| conditions: ctx.nitro.options.exportConditions, | ||
| externalConditions: ctx.nitro.options.exportConditions | ||
| }, | ||
| dev: { createEnvironment: (envName, envConfig) => createFetchableDevEnvironment(envName, envConfig, ctx.devWorker, tryResolve(serviceConfig.entry)) } | ||
| }; | ||
| } | ||
| function createServiceEnvironments(ctx) { | ||
| return Object.fromEntries(Object.entries(ctx.services).map(([name, config]) => [name, createServiceEnvironment(ctx, name, config)])); | ||
| } | ||
| function tryResolve(id) { | ||
| if (/^[~#/\0]/.test(id) || isAbsolute$1(id)) return id; | ||
| return resolveModulePath(id, { | ||
| suffixes: ["", "/index"], | ||
| extensions: [ | ||
| "", | ||
| ".ts", | ||
| ".mjs", | ||
| ".cjs", | ||
| ".js", | ||
| ".mts", | ||
| ".cts" | ||
| ], | ||
| try: true | ||
| }) || id; | ||
| } | ||
| //#endregion | ||
| //#region src/build/vite/preview.ts | ||
| function nitroPreviewPlugin(ctx) { | ||
| return { | ||
| name: "nitro:preview", | ||
| apply: (_config, configEnv) => !!configEnv.isPreview, | ||
| config(config) { | ||
| return { preview: { port: config.preview?.port || 3e3 } }; | ||
| }, | ||
| async configurePreviewServer(server) { | ||
| const { outputDir, buildInfo } = await getBuildInfo(server.config.root); | ||
| if (!buildInfo) throw this.error("Cannot load nitro build info. Make sure to build first."); | ||
| const info = [ | ||
| ["Build Directory:", prettyPath(outputDir)], | ||
| ["Date:", buildInfo.date && new Date(buildInfo.date).toLocaleString()], | ||
| ["Nitro Version:", buildInfo.versions.nitro], | ||
| ["Nitro Preset:", buildInfo.preset], | ||
| buildInfo.framework?.name !== "nitro" && ["Framework:", buildInfo.framework?.name + (buildInfo.framework?.version ? ` (v${buildInfo.framework.version})` : "")] | ||
| ].filter((i) => i && i[1]); | ||
| consola$1.box({ | ||
| title: " [Build Info] ", | ||
| message: info.map((i) => `- ${i[0]} ${i[1]}`).join("\n") | ||
| }); | ||
| if (!buildInfo.commands?.preview) { | ||
| consola$1.warn("No nitro build preview command found for this preset."); | ||
| return; | ||
| } | ||
| const dotEnvEntries = await loadPreviewDotEnv(server.config.root); | ||
| if (dotEnvEntries.length > 0) consola$1.box({ | ||
| title: " [Environment Variables] ", | ||
| message: [ | ||
| "Loaded variables from .env files (preview mode only).", | ||
| "Set platform environment variables for production:", | ||
| ...dotEnvEntries.map(([key, val]) => ` - ${key}`) | ||
| ].join("\n") | ||
| }); | ||
| const [command, ...args] = buildInfo.commands.preview.split(" "); | ||
| consola$1.info(`Spawning preview server...`); | ||
| consola$1.info(buildInfo.commands?.preview); | ||
| console.log(""); | ||
| const { getRandomPort } = await import("get-port-please"); | ||
| const randomPort = await getRandomPort(); | ||
| const child = spawn(command, args, { | ||
| stdio: "inherit", | ||
| cwd: outputDir, | ||
| env: { | ||
| ...process.env, | ||
| ...Object.fromEntries(dotEnvEntries), | ||
| PORT: String(randomPort) | ||
| } | ||
| }); | ||
| for (const sig of ["SIGINT", "SIGHUP"]) process.once(sig, () => { | ||
| consola$1.info(`Stopping preview server...`); | ||
| if (child.killed === false) { | ||
| child.kill(sig); | ||
| process.exit(); | ||
| } | ||
| }); | ||
| child.on("exit", (code) => { | ||
| if (code && code !== 0) consola$1.error(`[nitro] Preview server exited with code ${code}`); | ||
| }); | ||
| const { createProxyServer } = await import("../cli/_chunks/dist3.mjs"); | ||
| const proxy = createProxyServer({ target: `http://localhost:${randomPort}` }); | ||
| server.middlewares.use((req, res, next) => { | ||
| if (child && !child.killed) proxy.web(req, res).catch(next); | ||
| else res.end(`Nitro preview server is not running.`); | ||
| }); | ||
| } | ||
| }; | ||
| } | ||
| async function loadPreviewDotEnv(root) { | ||
| const { loadDotenv } = await import("../cli/_chunks/dist2.mjs"); | ||
| const env = await loadDotenv({ | ||
| cwd: root, | ||
| fileName: [ | ||
| ".env.preview", | ||
| ".env.production", | ||
| ".env" | ||
| ] | ||
| }); | ||
| return Object.entries(env).filter(([_key, val]) => val); | ||
| } | ||
| //#endregion | ||
| //#region src/build/vite/plugin.ts | ||
| const DEFAULT_EXTENSIONS = [ | ||
| ".ts", | ||
| ".js", | ||
| ".mts", | ||
| ".mjs", | ||
| ".tsx", | ||
| ".jsx" | ||
| ]; | ||
| const debug = process.env.NITRO_DEBUG ? (...args) => console.log("[nitro]", ...args) : () => {}; | ||
| function nitro(pluginConfig = {}) { | ||
| const ctx = createContext(pluginConfig); | ||
| return [ | ||
| nitroInit(ctx), | ||
| nitroEnv(ctx), | ||
| nitroMain(ctx), | ||
| nitroPrepare(ctx), | ||
| nitroService(ctx), | ||
| nitroPreviewPlugin(ctx), | ||
| pluginConfig.experimental?.vite?.assetsImport !== false && assetsPlugin({ experimental: { clientBuildFallback: false } }) | ||
| ].filter(Boolean); | ||
| } | ||
| function nitroInit(ctx) { | ||
| return { | ||
| name: "nitro:init", | ||
| sharedDuringBuild: true, | ||
| apply: (_config, configEnv) => !configEnv.isPreview, | ||
| async config(config, configEnv) { | ||
| ctx._isRolldown = !!this.meta.rolldownVersion; | ||
| if (!ctx._initialized) { | ||
| debug("[init] Initializing nitro"); | ||
| ctx._initialized = true; | ||
| await setupNitroContext(ctx, configEnv, config); | ||
| } | ||
| }, | ||
| applyToEnvironment(env) { | ||
| if (env.name === "nitro" && ctx.nitro?.options.dev) { | ||
| debug("[init] Adding rollup plugins for dev"); | ||
| return [...ctx.rollupConfig?.config.plugins || []]; | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function nitroEnv(ctx) { | ||
| return { | ||
| name: "nitro:env", | ||
| sharedDuringBuild: true, | ||
| apply: (_config, configEnv) => !configEnv.isPreview, | ||
| async config(userConfig, _configEnv) { | ||
| debug("[env] Extending config (environments)"); | ||
| const environments = { | ||
| ...createServiceEnvironments(ctx), | ||
| nitro: createNitroEnvironment(ctx) | ||
| }; | ||
| environments.client = { | ||
| consumer: userConfig.environments?.client?.consumer ?? "client", | ||
| build: { rollupOptions: { input: userConfig.environments?.client?.build?.rollupOptions?.input ?? useNitro(ctx).options.renderer?.template } } | ||
| }; | ||
| debug("[env] Environments:", Object.keys(environments).join(", ")); | ||
| return { environments }; | ||
| }, | ||
| configEnvironment(name, config) { | ||
| if (config.consumer === "client") { | ||
| debug("[env] Configuring client environment", name === "client" ? "" : ` (${name})`); | ||
| config.build.emptyOutDir = false; | ||
| config.build.outDir = useNitro(ctx).options.output.publicDir; | ||
| } else if (ctx.pluginConfig.experimental?.vite?.virtualBundle && name in (ctx.services || {})) { | ||
| debug("[env] Configuring service environment for virtual:", name); | ||
| config.build ??= {}; | ||
| config.build.write = config.build.write ?? false; | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function nitroMain(ctx) { | ||
| return { | ||
| name: "nitro:main", | ||
| sharedDuringBuild: true, | ||
| apply: (_config, configEnv) => !configEnv.isPreview, | ||
| async config(userConfig, _configEnv) { | ||
| debug("[main] Extending config (appType, resolve, server)"); | ||
| if (!ctx.rollupConfig) throw new Error("Nitro rollup config is not initialized yet."); | ||
| return { | ||
| appType: userConfig.appType || "custom", | ||
| resolve: { alias: ctx.rollupConfig.base.aliases }, | ||
| builder: { sharedConfigBuild: true }, | ||
| experimental: { enableNativePlugin: false }, | ||
| server: { | ||
| port: Number.parseInt(process.env.PORT || "") || userConfig.server?.port || useNitro(ctx).options.devServer?.port || 3e3, | ||
| cors: false | ||
| } | ||
| }; | ||
| }, | ||
| buildApp: { | ||
| order: "post", | ||
| handler(builder) { | ||
| debug("[main] Building environments"); | ||
| return buildEnvironments(ctx, builder); | ||
| } | ||
| }, | ||
| generateBundle: { handler(_options, bundle) { | ||
| const environment = this.environment; | ||
| debug("[main] Generating manifest and entry points for environment:", environment.name); | ||
| const isRegisteredService = Object.keys(ctx.services).includes(environment.name); | ||
| let entryFile; | ||
| for (const [_name, file] of Object.entries(bundle)) if (file.type === "chunk" && isRegisteredService && file.isEntry) if (entryFile === void 0) entryFile = file.fileName; | ||
| else this.warn(`Multiple entry points found for service "${environment.name}"`); | ||
| if (isRegisteredService) { | ||
| if (entryFile === void 0) this.error(`No entry point found for service "${this.environment.name}".`); | ||
| ctx._entryPoints[this.environment.name] = entryFile; | ||
| ctx._serviceBundles[this.environment.name] = bundle; | ||
| } | ||
| } }, | ||
| configureServer: (server) => { | ||
| debug("[main] Configuring dev server"); | ||
| return configureViteDevServer(ctx, server); | ||
| }, | ||
| async hotUpdate({ server, modules, timestamp }) { | ||
| const env = this.environment; | ||
| if (ctx.pluginConfig.experimental?.vite.serverReload === false || env.config.consumer === "client") return; | ||
| const clientEnvs = Object.values(server.environments).filter((env$1) => env$1.config.consumer === "client"); | ||
| let hasServerOnlyModule = false; | ||
| const invalidated = /* @__PURE__ */ new Set(); | ||
| for (const mod of modules) if (mod.id && !clientEnvs.some((env$1) => env$1.moduleGraph.getModuleById(mod.id))) { | ||
| hasServerOnlyModule = true; | ||
| env.moduleGraph.invalidateModule(mod, invalidated, timestamp, false); | ||
| } | ||
| if (hasServerOnlyModule) { | ||
| env.hot.send({ type: "full-reload" }); | ||
| server.ws.send({ type: "full-reload" }); | ||
| return []; | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function nitroPrepare(ctx) { | ||
| return { | ||
| name: "nitro:prepare", | ||
| sharedDuringBuild: true, | ||
| applyToEnvironment: (env) => env.name === "nitro", | ||
| buildApp: { | ||
| order: "pre", | ||
| async handler() { | ||
| debug("[prepare] Preparing output directory"); | ||
| const nitro$1 = ctx.nitro; | ||
| await prepare(nitro$1); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function nitroService(ctx) { | ||
| return { | ||
| name: "nitro:service", | ||
| enforce: "pre", | ||
| sharedDuringBuild: true, | ||
| applyToEnvironment: (env) => env.name === "nitro", | ||
| resolveId: { async handler(id) { | ||
| if (id === "#nitro-vite-setup") return { | ||
| id, | ||
| moduleSideEffects: true | ||
| }; | ||
| } }, | ||
| load: { async handler(id) { | ||
| if (id === "#nitro-vite-setup") return prodSetup(ctx); | ||
| } } | ||
| }; | ||
| } | ||
| function createContext(pluginConfig) { | ||
| return { | ||
| pluginConfig, | ||
| services: {}, | ||
| _entryPoints: {}, | ||
| _serviceBundles: {} | ||
| }; | ||
| } | ||
| function useNitro(ctx) { | ||
| if (!ctx.nitro) throw new Error("Nitro instance is not initialized yet."); | ||
| return ctx.nitro; | ||
| } | ||
| async function setupNitroContext(ctx, configEnv, userConfig) { | ||
| const nitroConfig = { | ||
| dev: configEnv.command === "serve", | ||
| rootDir: userConfig.root, | ||
| ...defu(ctx.pluginConfig, ctx.pluginConfig.config, userConfig.nitro) | ||
| }; | ||
| nitroConfig.modules ??= []; | ||
| for (const plugin of flattenPlugins(userConfig.plugins || [])) if (plugin.nitro) nitroConfig.modules.push(plugin.nitro); | ||
| nitroConfig.builder = ctx._isRolldown ? "rolldown-vite" : "vite"; | ||
| debug("[init] Using builder:", nitroConfig.builder); | ||
| ctx.nitro = ctx.pluginConfig._nitro || await createNitro(nitroConfig); | ||
| ctx.nitro.options.builder = ctx._isRolldown ? "rolldown-vite" : "vite"; | ||
| if (!ctx.services?.ssr) if (userConfig.environments?.ssr === void 0) { | ||
| const ssrEntry = resolveModulePath("./entry-server", { | ||
| from: [ | ||
| "app", | ||
| "src", | ||
| "" | ||
| ].flatMap((d) => [ctx.nitro.options.rootDir, ...ctx.nitro.options.scanDirs].map((s) => join$1(s, d) + "/")), | ||
| extensions: DEFAULT_EXTENSIONS, | ||
| try: true | ||
| }); | ||
| if (ssrEntry) { | ||
| ctx.services.ssr = { entry: ssrEntry }; | ||
| ctx.nitro.logger.info(`Using \`${prettyPath(ssrEntry)}\` as vite ssr entry.`); | ||
| } | ||
| } else { | ||
| let ssrEntry = getEntry(userConfig.environments.ssr.build?.rollupOptions?.input); | ||
| if (typeof ssrEntry === "string") { | ||
| ssrEntry = resolveModulePath(ssrEntry, { | ||
| from: [ctx.nitro.options.rootDir, ...ctx.nitro.options.scanDirs], | ||
| extensions: DEFAULT_EXTENSIONS, | ||
| suffixes: ["", "/index"], | ||
| try: true | ||
| }) || ssrEntry; | ||
| ctx.services.ssr = { entry: ssrEntry }; | ||
| } | ||
| } | ||
| if (!ctx.nitro.options.renderer?.handler && !ctx.nitro.options.renderer?.template && ctx.services.ssr?.entry) { | ||
| ctx.nitro.options.renderer ??= {}; | ||
| ctx.nitro.options.renderer.handler = resolve$1(runtimeDir, "internal/vite/ssr-renderer"); | ||
| ctx.nitro.routing.sync(); | ||
| } | ||
| const publicDistDir = ctx._publicDistDir = userConfig.build?.outDir || resolve$1(ctx.nitro.options.buildDir, "vite/public"); | ||
| ctx.nitro.options.publicAssets.push({ | ||
| dir: publicDistDir, | ||
| maxAge: 0, | ||
| baseURL: "/", | ||
| fallthrough: true | ||
| }); | ||
| if (!ctx.nitro.options.dev) ctx.nitro.options.unenv.push({ | ||
| meta: { name: "nitro-vite" }, | ||
| polyfill: ["#nitro-vite-setup"] | ||
| }); | ||
| await ctx.nitro.hooks.callHook("build:before", ctx.nitro); | ||
| ctx.rollupConfig = await getViteRollupConfig(ctx); | ||
| await ctx.nitro.hooks.callHook("rollup:before", ctx.nitro, ctx.rollupConfig.config); | ||
| if (ctx.nitro.options.dev && !ctx.devWorker) { | ||
| ctx.devWorker = createDevWorker(ctx); | ||
| ctx.nitro.fetch = (req) => ctx.devWorker.fetch(req); | ||
| } | ||
| if (ctx.nitro.options.dev && !ctx.devApp) ctx.devApp = new NitroDevApp(ctx.nitro); | ||
| } | ||
| function getEntry(input) { | ||
| if (typeof input === "string") return input; | ||
| else if (Array.isArray(input) && input.length > 0) return input[0]; | ||
| else if (input && "index" in input) return input.index; | ||
| } | ||
| function flattenPlugins(plugins) { | ||
| return plugins.flatMap((plugin) => Array.isArray(plugin) ? flattenPlugins(plugin) : [plugin]).filter((p) => p && !(p instanceof Promise)); | ||
| } | ||
| //#endregion | ||
| export { nitro as t }; |
| import { i as __toESM } from "./Bqks5huO.mjs"; | ||
| import { C as isAbsolute, O as relative, h as resolveModulePath, k as resolve, w as join, x as dirname } from "../_libs/c12.mjs"; | ||
| import { c as parseNodeModulePath, s as lookupNodeModuleSubpath } from "../_libs/local-pkg.mjs"; | ||
| import { o as toExports } from "../_libs/unimport.mjs"; | ||
| import { t as glob } from "../_libs/tinyglobby.mjs"; | ||
| import { i as writeFile, r as resolveNitroPath, t as isDirectory } from "./C7CbzoI1.mjs"; | ||
| import { t as resolveAlias } from "../_libs/pathe.mjs"; | ||
| import { n as resolveSchema, t as generateTypes } from "../_libs/untyped.mjs"; | ||
| import { existsSync, promises } from "node:fs"; | ||
| import { withBase, withLeadingSlash, withoutTrailingSlash } from "ufo"; | ||
| import { defu } from "defu"; | ||
| import { runtimeDir } from "nitro/meta"; | ||
| //#region src/scan.ts | ||
| const GLOB_SCAN_PATTERN = "**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}"; | ||
| const suffixRegex = /(\.(?<method>connect|delete|get|head|options|patch|post|put|trace))?(\.(?<env>dev|prod|prerender))?$/; | ||
| async function scanAndSyncOptions(nitro) { | ||
| const scannedPlugins = await scanPlugins(nitro); | ||
| for (const plugin of scannedPlugins) if (!nitro.options.plugins.includes(plugin)) nitro.options.plugins.push(plugin); | ||
| if (nitro.options.experimental.tasks) { | ||
| const scannedTasks = await scanTasks(nitro); | ||
| for (const scannedTask of scannedTasks) if (scannedTask.name in nitro.options.tasks) { | ||
| if (!nitro.options.tasks[scannedTask.name].handler) nitro.options.tasks[scannedTask.name].handler = scannedTask.handler; | ||
| } else nitro.options.tasks[scannedTask.name] = { | ||
| handler: scannedTask.handler, | ||
| description: "" | ||
| }; | ||
| } | ||
| const scannedModules = await scanModules(nitro); | ||
| nitro.options.modules = nitro.options.modules || []; | ||
| for (const modPath of scannedModules) if (!nitro.options.modules.includes(modPath)) nitro.options.modules.push(modPath); | ||
| } | ||
| async function scanHandlers(nitro) { | ||
| const middleware = await scanMiddleware(nitro); | ||
| const handlers = await Promise.all([scanServerRoutes(nitro, nitro.options.apiDir || "api", nitro.options.apiBaseURL || "/api"), scanServerRoutes(nitro, nitro.options.routesDir || "routes")]).then((r) => r.flat()); | ||
| nitro.scannedHandlers = [...middleware, ...handlers.filter((h, index, array) => { | ||
| return array.findIndex((h2) => h.route === h2.route && h.method === h2.method && h.env === h2.env) === index; | ||
| })]; | ||
| return handlers; | ||
| } | ||
| async function scanMiddleware(nitro) { | ||
| return (await scanFiles(nitro, "middleware")).map((file) => { | ||
| return { | ||
| route: "/**", | ||
| middleware: true, | ||
| handler: file.fullPath | ||
| }; | ||
| }); | ||
| } | ||
| async function scanServerRoutes(nitro, dir, prefix = "/") { | ||
| return (await scanFiles(nitro, dir)).map((file) => { | ||
| let route = file.path.replace(/\.[A-Za-z]+$/, "").replace(/\(([^(/\\]+)\)[/\\]/g, "").replace(/\[\.{3}]/g, "**").replace(/\[\.{3}(\w+)]/g, "**:$1").replace(/\[([^/\]]+)]/g, ":$1"); | ||
| route = withLeadingSlash(withoutTrailingSlash(withBase(route, prefix))); | ||
| const suffixMatch = route.match(suffixRegex); | ||
| let method; | ||
| let env; | ||
| if (suffixMatch?.index && suffixMatch?.index >= 0) { | ||
| route = route.slice(0, suffixMatch.index); | ||
| method = suffixMatch.groups?.method; | ||
| env = suffixMatch.groups?.env; | ||
| } | ||
| route = route.replace(/\/index$/, "") || "/"; | ||
| return { | ||
| handler: file.fullPath, | ||
| lazy: true, | ||
| middleware: false, | ||
| route, | ||
| method, | ||
| env | ||
| }; | ||
| }); | ||
| } | ||
| async function scanPlugins(nitro) { | ||
| return (await scanFiles(nitro, "plugins")).map((f) => f.fullPath); | ||
| } | ||
| async function scanTasks(nitro) { | ||
| return (await scanFiles(nitro, "tasks")).map((f) => { | ||
| return { | ||
| name: f.path.replace(/\/index$/, "").replace(/\.[A-Za-z]+$/, "").replace(/\//g, ":"), | ||
| handler: f.fullPath | ||
| }; | ||
| }); | ||
| } | ||
| async function scanModules(nitro) { | ||
| return (await scanFiles(nitro, "modules")).map((f) => f.fullPath); | ||
| } | ||
| async function scanFiles(nitro, name) { | ||
| return await Promise.all(nitro.options.scanDirs.map((dir) => scanDir(nitro, dir, name))).then((r) => r.flat()); | ||
| } | ||
| async function scanDir(nitro, dir, name) { | ||
| return (await glob(join(name, GLOB_SCAN_PATTERN), { | ||
| cwd: dir, | ||
| dot: true, | ||
| ignore: nitro.options.ignore, | ||
| absolute: true | ||
| }).catch((error) => { | ||
| if (error?.code === "ENOTDIR") { | ||
| nitro.logger.warn(`Ignoring \`${join(dir, name)}\`. It must be a directory.`); | ||
| return []; | ||
| } | ||
| throw error; | ||
| })).map((fullPath) => { | ||
| return { | ||
| fullPath, | ||
| path: relative(join(dir, name), fullPath) | ||
| }; | ||
| }).sort((a, b) => a.path.localeCompare(b.path)); | ||
| } | ||
| //#endregion | ||
| //#region src/build/types.ts | ||
| async function writeTypes(nitro) { | ||
| const types = { routes: {} }; | ||
| const generatedTypesDir = resolve(nitro.options.rootDir, nitro.options.typescript.generatedTypesDir || "node_modules/.nitro/types"); | ||
| const middleware = [...nitro.scannedHandlers, ...nitro.options.handlers]; | ||
| for (const mw of middleware) { | ||
| if (typeof mw.handler !== "string" || !mw.route) continue; | ||
| const relativePath = relative(generatedTypesDir, resolveNitroPath(mw.handler, nitro.options)).replace(/\.(js|mjs|cjs|ts|mts|cts|tsx|jsx)$/, ""); | ||
| const method = mw.method || "default"; | ||
| types.routes[mw.route] ??= {}; | ||
| types.routes[mw.route][method] ??= []; | ||
| types.routes[mw.route][method].push(`Simplify<Serialize<Awaited<ReturnType<typeof import('${relativePath}').default>>>>`); | ||
| } | ||
| let autoImportedTypes = []; | ||
| let autoImportExports = ""; | ||
| if (nitro.unimport) { | ||
| await nitro.unimport.init(); | ||
| const allImports = await nitro.unimport.getImports(); | ||
| autoImportExports = toExports(allImports).replace(/#internal\/nitro/g, relative(generatedTypesDir, runtimeDir)); | ||
| const resolvedImportPathMap = /* @__PURE__ */ new Map(); | ||
| for (const i of allImports) { | ||
| const from = i.typeFrom || i.from; | ||
| if (resolvedImportPathMap.has(from)) continue; | ||
| let path = resolveAlias(from, nitro.options.alias); | ||
| if (!isAbsolute(path)) { | ||
| const resolvedPath = resolveModulePath(from, { | ||
| try: true, | ||
| from: nitro.options.nodeModulesDirs, | ||
| conditions: [ | ||
| "type", | ||
| "node", | ||
| "import" | ||
| ], | ||
| suffixes: ["", "/index"], | ||
| extensions: [ | ||
| ".mjs", | ||
| ".cjs", | ||
| ".js", | ||
| ".mts", | ||
| ".cts", | ||
| ".ts" | ||
| ] | ||
| }); | ||
| if (resolvedPath) { | ||
| const { dir, name } = parseNodeModulePath(resolvedPath); | ||
| if (!dir || !name) path = resolvedPath; | ||
| else path = join(dir, name, await lookupNodeModuleSubpath(resolvedPath) || ""); | ||
| } | ||
| } | ||
| if (existsSync(path) && !await isDirectory(path)) path = path.replace(/\.[a-z]+$/, ""); | ||
| if (isAbsolute(path)) path = relative(generatedTypesDir, path); | ||
| resolvedImportPathMap.set(from, path); | ||
| } | ||
| autoImportedTypes = [nitro.options.imports && nitro.options.imports.autoImport !== false ? (await nitro.unimport.generateTypeDeclarations({ | ||
| exportHelper: false, | ||
| resolvePath: (i) => { | ||
| const from = i.typeFrom || i.from; | ||
| return resolvedImportPathMap.get(from) ?? from; | ||
| } | ||
| })).trim() : ""]; | ||
| } | ||
| const generateRoutes = () => [ | ||
| "// Generated by nitro", | ||
| "import type { Serialize, Simplify } from \"nitro/types\";", | ||
| "declare module \"nitro/types\" {", | ||
| " type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T", | ||
| " interface InternalApi {", | ||
| ...Object.entries(types.routes).map(([path, methods]) => [ | ||
| ` '${path}': {`, | ||
| ...Object.entries(methods).map(([method, types$1]) => ` '${method}': ${types$1.join(" | ")}`), | ||
| " }" | ||
| ].join("\n")), | ||
| " }", | ||
| "}", | ||
| "export {}" | ||
| ]; | ||
| const config = [ | ||
| "// Generated by nitro", | ||
| `declare module "nitro/types" {`, | ||
| nitro.options.typescript.generateRuntimeConfigTypes ? generateTypes(await resolveSchema(Object.fromEntries(Object.entries(nitro.options.runtimeConfig).filter(([key]) => !["app", "nitro"].includes(key)))), { | ||
| interfaceName: "NitroRuntimeConfig", | ||
| addExport: false, | ||
| addDefaults: false, | ||
| allowExtraKeys: false, | ||
| indentation: 2 | ||
| }) : "", | ||
| `}`, | ||
| "export {}" | ||
| ]; | ||
| const declarations = [ | ||
| "/// <reference path=\"./nitro-routes.d.ts\" />", | ||
| "/// <reference path=\"./nitro-config.d.ts\" />", | ||
| "/// <reference path=\"./nitro-imports.d.ts\" />" | ||
| ]; | ||
| const buildFiles = []; | ||
| buildFiles.push({ | ||
| path: join(generatedTypesDir, "nitro-routes.d.ts"), | ||
| contents: () => generateRoutes().join("\n") | ||
| }); | ||
| buildFiles.push({ | ||
| path: join(generatedTypesDir, "nitro-config.d.ts"), | ||
| contents: config.join("\n") | ||
| }); | ||
| buildFiles.push({ | ||
| path: join(generatedTypesDir, "nitro-imports.d.ts"), | ||
| contents: [...autoImportedTypes, autoImportExports || "export {}"].join("\n") | ||
| }); | ||
| buildFiles.push({ | ||
| path: join(generatedTypesDir, "nitro.d.ts"), | ||
| contents: declarations.join("\n") | ||
| }); | ||
| if (nitro.options.typescript.generateTsConfig) { | ||
| const tsConfigPath = resolve(generatedTypesDir, nitro.options.typescript.tsconfigPath); | ||
| const tsconfigDir = dirname(tsConfigPath); | ||
| const tsConfig = defu(nitro.options.typescript.tsConfig, { | ||
| compilerOptions: { | ||
| esModuleInterop: true, | ||
| allowSyntheticDefaultImports: true, | ||
| skipLibCheck: true, | ||
| target: "ESNext", | ||
| allowJs: true, | ||
| resolveJsonModule: true, | ||
| moduleDetection: "force", | ||
| isolatedModules: true, | ||
| verbatimModuleSyntax: true, | ||
| allowImportingTsExtensions: true, | ||
| strict: nitro.options.typescript.strict, | ||
| noUncheckedIndexedAccess: true, | ||
| noImplicitOverride: true, | ||
| forceConsistentCasingInFileNames: true, | ||
| module: "Preserve", | ||
| jsx: "preserve", | ||
| jsxFactory: "h", | ||
| jsxFragmentFactory: "Fragment", | ||
| paths: { "#imports": [relativeWithDot(tsconfigDir, join(generatedTypesDir, "nitro-imports"))] } | ||
| }, | ||
| include: [ | ||
| relativeWithDot(tsconfigDir, join(generatedTypesDir, "nitro.d.ts")).replace(/^(?=[^.])/, "./"), | ||
| join(relativeWithDot(tsconfigDir, nitro.options.rootDir), "**/*"), | ||
| ...!nitro.options.serverDir || nitro.options.serverDir === nitro.options.rootDir ? [] : [join(relativeWithDot(tsconfigDir, nitro.options.serverDir), "**/*")] | ||
| ] | ||
| }); | ||
| for (const alias in tsConfig.compilerOptions.paths) { | ||
| const paths = await Promise.all(tsConfig.compilerOptions.paths[alias].map(async (path) => { | ||
| if (!isAbsolute(path)) return path; | ||
| return relativeWithDot(tsconfigDir, (await promises.stat(path).catch(() => null))?.isFile() ? path.replace(/(?<=\w)\.\w+$/g, "") : path); | ||
| })); | ||
| tsConfig.compilerOptions.paths[alias] = [...new Set(paths)]; | ||
| } | ||
| tsConfig.include = [...new Set(tsConfig.include.map((p) => isAbsolute(p) ? relativeWithDot(tsconfigDir, p) : p))]; | ||
| if (tsConfig.exclude) tsConfig.exclude = [...new Set(tsConfig.exclude.map((p) => isAbsolute(p) ? relativeWithDot(tsconfigDir, p) : p))]; | ||
| types.tsConfig = tsConfig; | ||
| buildFiles.push({ | ||
| path: tsConfigPath, | ||
| contents: () => JSON.stringify(tsConfig, null, 2) | ||
| }); | ||
| } | ||
| await nitro.hooks.callHook("types:extend", types); | ||
| await Promise.all(buildFiles.map(async (file) => { | ||
| await writeFile(resolve(generatedTypesDir, file.path), typeof file.contents === "string" ? file.contents : file.contents()); | ||
| })); | ||
| } | ||
| const RELATIVE_RE = /^\.{1,2}\//; | ||
| function relativeWithDot(from, to) { | ||
| const rel = relative(from, to); | ||
| return RELATIVE_RE.test(rel) ? rel : "./" + rel; | ||
| } | ||
| //#endregion | ||
| //#region src/utils/parallel.ts | ||
| async function runParallel(inputs, cb, opts) { | ||
| const tasks = /* @__PURE__ */ new Set(); | ||
| function queueNext() { | ||
| const route = inputs.values().next().value; | ||
| if (!route) return; | ||
| inputs.delete(route); | ||
| const task = (opts.interval ? new Promise((resolve$1) => setTimeout(resolve$1, opts.interval)) : Promise.resolve()).then(() => cb(route)).catch((error) => { | ||
| console.error(error); | ||
| }); | ||
| tasks.add(task); | ||
| return task.then(() => { | ||
| tasks.delete(task); | ||
| if (inputs.size > 0) return refillQueue(); | ||
| }); | ||
| } | ||
| function refillQueue() { | ||
| const workers = Math.min(opts.concurrency - tasks.size, inputs.size); | ||
| return Promise.all(Array.from({ length: workers }, () => queueNext())); | ||
| } | ||
| await refillQueue(); | ||
| } | ||
| //#endregion | ||
| export { scanHandlers as i, writeTypes as n, scanAndSyncOptions as r, runParallel as t }; |
| import { i as __toESM } from "./Bqks5huO.mjs"; | ||
| import { O as relative, T as normalize, g as resolveModuleURL, h as resolveModulePath, i as loadConfig, k as resolve, l as findWorkspaceDir, t as watchConfig, w as join } from "../_libs/c12.mjs"; | ||
| import { a as createUnimport } from "../_libs/unimport.mjs"; | ||
| import { t as glob } from "../_libs/tinyglobby.mjs"; | ||
| import { n as resolveCompatibilityDates, r as resolveCompatibilityDatesFromEnv } from "../_libs/compatx.mjs"; | ||
| import { t as klona } from "../_libs/klona.mjs"; | ||
| import { i as d, r as a } from "../_libs/std-env.mjs"; | ||
| import { t as escapeStringRegexp } from "../_libs/escape-string-regexp.mjs"; | ||
| import { n as parse, t as TSConfckCache } from "../_libs/tsconfck.mjs"; | ||
| import { i as writeFile$1, n as prettyPath, r as resolveNitroPath, t as isDirectory } from "./C7CbzoI1.mjs"; | ||
| import { i as scanHandlers, r as scanAndSyncOptions, t as runParallel } from "./ANM1K1bE.mjs"; | ||
| import { a as findRoute, i as findAllRoutes, n as addRoute, r as createRouter, t as compileRouterToString } from "../_libs/rou3.mjs"; | ||
| import { t as src_default } from "../_libs/mime.mjs"; | ||
| import { n as z, t as P } from "../_libs/ultrahtml.mjs"; | ||
| import { createRequire } from "node:module"; | ||
| import consola$1, { consola } from "consola"; | ||
| import { Hookable, createDebugger } from "hookable"; | ||
| import { existsSync, promises } from "node:fs"; | ||
| import { joinURL, parseURL, withBase, withLeadingSlash, withTrailingSlash, withoutBase, withoutTrailingSlash } from "ufo"; | ||
| import { pathToFileURL } from "node:url"; | ||
| import fsp, { readFile } from "node:fs/promises"; | ||
| import { defu } from "defu"; | ||
| import { pkgDir, runtimeDir } from "nitro/meta"; | ||
| import { colors } from "consola/utils"; | ||
| import { ofetch } from "ofetch"; | ||
| import { hash } from "ohash"; | ||
| import zlib from "node:zlib"; | ||
| import { toRequest } from "h3"; | ||
| //#region src/config/defaults.ts | ||
| const NitroDefaults = { | ||
| compatibilityDate: "latest", | ||
| debug: d, | ||
| logLevel: a ? 1 : 3, | ||
| runtimeConfig: { | ||
| app: {}, | ||
| nitro: {} | ||
| }, | ||
| serverDir: false, | ||
| scanDirs: [], | ||
| buildDir: `node_modules/.nitro`, | ||
| output: { | ||
| dir: "{{ rootDir }}/.output", | ||
| serverDir: "{{ output.dir }}/server", | ||
| publicDir: "{{ output.dir }}/public" | ||
| }, | ||
| features: {}, | ||
| experimental: {}, | ||
| future: {}, | ||
| storage: {}, | ||
| devStorage: {}, | ||
| publicAssets: [], | ||
| serverAssets: [], | ||
| plugins: [], | ||
| tasks: {}, | ||
| scheduledTasks: {}, | ||
| imports: false, | ||
| virtual: {}, | ||
| compressPublicAssets: false, | ||
| ignore: [], | ||
| dev: false, | ||
| devServer: { watch: [] }, | ||
| watchOptions: { ignoreInitial: true }, | ||
| devProxy: {}, | ||
| logging: { | ||
| compressedSizes: true, | ||
| buildSuccess: true | ||
| }, | ||
| baseURL: process.env.NITRO_APP_BASE_URL || "/", | ||
| handlers: [], | ||
| devHandlers: [], | ||
| errorHandler: void 0, | ||
| routes: {}, | ||
| routeRules: {}, | ||
| prerender: { | ||
| autoSubfolderIndex: true, | ||
| concurrency: 1, | ||
| interval: 0, | ||
| retry: 3, | ||
| retryDelay: 500, | ||
| failOnError: false, | ||
| crawlLinks: false, | ||
| ignore: [], | ||
| routes: [] | ||
| }, | ||
| builder: void 0, | ||
| moduleSideEffects: ["unenv/polyfill/"], | ||
| replace: {}, | ||
| node: true, | ||
| sourcemap: false, | ||
| typescript: { | ||
| strict: true, | ||
| generateRuntimeConfigTypes: false, | ||
| generateTsConfig: false, | ||
| tsconfigPath: "tsconfig.json", | ||
| tsConfig: void 0 | ||
| }, | ||
| nodeModulesDirs: [], | ||
| hooks: {}, | ||
| commands: {}, | ||
| framework: { | ||
| name: "nitro", | ||
| version: "" | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/config/resolvers/assets.ts | ||
| async function resolveAssetsOptions(options) { | ||
| for (const publicAsset of options.publicAssets) { | ||
| publicAsset.dir = resolve(options.rootDir, publicAsset.dir); | ||
| publicAsset.baseURL = withLeadingSlash(withoutTrailingSlash(publicAsset.baseURL || "/")); | ||
| } | ||
| for (const dir of [options.rootDir, ...options.scanDirs]) { | ||
| const publicDir = resolve(dir, "public"); | ||
| if (!existsSync(publicDir)) continue; | ||
| if (options.publicAssets.some((asset) => asset.dir === publicDir)) continue; | ||
| options.publicAssets.push({ dir: publicDir }); | ||
| } | ||
| for (const serverAsset of options.serverAssets) serverAsset.dir = resolve(options.rootDir, serverAsset.dir); | ||
| options.serverAssets.push({ | ||
| baseName: "server", | ||
| dir: resolve(options.rootDir, "assets") | ||
| }); | ||
| for (const asset of options.publicAssets) { | ||
| asset.baseURL = asset.baseURL || "/"; | ||
| const isTopLevel = asset.baseURL === "/"; | ||
| asset.fallthrough = asset.fallthrough ?? isTopLevel; | ||
| const routeRule = options.routeRules[asset.baseURL + "/**"]; | ||
| asset.maxAge = (routeRule?.cache)?.maxAge ?? asset.maxAge ?? 0; | ||
| if (asset.maxAge && !asset.fallthrough) options.routeRules[asset.baseURL + "/**"] = defu(routeRule, { headers: { "cache-control": `public, max-age=${asset.maxAge}, immutable` } }); | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/compatibility.ts | ||
| async function resolveCompatibilityOptions(options) { | ||
| options.compatibilityDate = resolveCompatibilityDatesFromEnv(options.compatibilityDate); | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/database.ts | ||
| async function resolveDatabaseOptions(options) { | ||
| if (options.experimental.database && options.imports) { | ||
| options.imports.presets.push({ | ||
| from: "nitro/database", | ||
| imports: ["useDatabase"] | ||
| }); | ||
| if (options.dev && !options.database && !options.devDatabase) options.devDatabase = { default: { | ||
| connector: "sqlite", | ||
| options: { cwd: options.rootDir } | ||
| } }; | ||
| else if (options.node && !options.database) options.database = { default: { | ||
| connector: "sqlite", | ||
| options: {} | ||
| } }; | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/export-conditions.ts | ||
| async function resolveExportConditionsOptions(options) { | ||
| options.exportConditions = _resolveExportConditions(options.exportConditions || [], { | ||
| dev: options.dev, | ||
| node: options.node, | ||
| wasm: options.experimental.wasm | ||
| }); | ||
| } | ||
| function _resolveExportConditions(conditions, opts) { | ||
| const resolvedConditions = []; | ||
| resolvedConditions.push(opts.dev ? "development" : "production"); | ||
| resolvedConditions.push(...conditions); | ||
| if (opts.node) resolvedConditions.push("node"); | ||
| else resolvedConditions.push("wintercg", "worker", "web", "browser", "workerd", "edge-light", "netlify", "edge-routine", "deno"); | ||
| if (opts.wasm) resolvedConditions.push("wasm", "unwasm"); | ||
| resolvedConditions.push("import", "default"); | ||
| if ("Bun" in globalThis) resolvedConditions.push("bun"); | ||
| else if ("Deno" in globalThis) resolvedConditions.push("deno"); | ||
| return resolvedConditions.filter((c, i) => resolvedConditions.indexOf(c) === i); | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/imports.ts | ||
| async function resolveImportsOptions(options) { | ||
| if (options.imports === false) return; | ||
| options.imports.presets ??= []; | ||
| options.imports.dirs ??= []; | ||
| options.imports.dirs.push(...options.scanDirs.map((dir) => join(dir, "utils/**/*"))); | ||
| if (Array.isArray(options.imports.exclude) && options.imports.exclude.length === 0) { | ||
| options.imports.exclude.push(/[/\\]\.git[/\\]/); | ||
| options.imports.exclude.push(options.buildDir); | ||
| const scanDirsInNodeModules = options.scanDirs.map((dir) => dir.match(/(?<=\/)node_modules\/(.+)$/)?.[1]).filter(Boolean); | ||
| options.imports.exclude.push(scanDirsInNodeModules.length > 0 ? /* @__PURE__ */ new RegExp(`node_modules\\/(?!${scanDirsInNodeModules.map((dir) => escapeStringRegexp(dir)).join("|")})`) : /[/\\]node_modules[/\\]/); | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/open-api.ts | ||
| async function resolveOpenAPIOptions(options) { | ||
| if (!options.experimental.openAPI) return; | ||
| if (!options.dev && !options.openAPI?.production) return; | ||
| const shouldPrerender = !options.dev && options.openAPI?.production === "prerender"; | ||
| const handlersEnv = shouldPrerender ? "prerender" : ""; | ||
| const prerenderRoutes = []; | ||
| const jsonRoute = options.openAPI?.route || "/_openapi.json"; | ||
| prerenderRoutes.push(jsonRoute); | ||
| options.handlers.push({ | ||
| route: jsonRoute, | ||
| env: handlersEnv, | ||
| handler: join(runtimeDir, "internal/routes/openapi") | ||
| }); | ||
| if (options.openAPI?.ui?.scalar !== false) { | ||
| const scalarRoute = options.openAPI?.ui?.scalar?.route || "/_scalar"; | ||
| prerenderRoutes.push(scalarRoute); | ||
| options.handlers.push({ | ||
| route: options.openAPI?.ui?.scalar?.route || "/_scalar", | ||
| env: handlersEnv, | ||
| handler: join(runtimeDir, "internal/routes/scalar") | ||
| }); | ||
| } | ||
| if (options.openAPI?.ui?.swagger !== false) { | ||
| const swaggerRoute = options.openAPI?.ui?.swagger?.route || "/_swagger"; | ||
| prerenderRoutes.push(swaggerRoute); | ||
| options.handlers.push({ | ||
| route: swaggerRoute, | ||
| env: handlersEnv, | ||
| handler: join(runtimeDir, "internal/routes/swagger") | ||
| }); | ||
| } | ||
| if (shouldPrerender) { | ||
| options.prerender ??= {}; | ||
| options.prerender.routes ??= []; | ||
| options.prerender.routes.push(...prerenderRoutes); | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/tsconfig.ts | ||
| async function resolveTsconfig(options) { | ||
| const root = resolve(options.rootDir || ".") + "/"; | ||
| if (!options.typescript.tsConfig) options.typescript.tsConfig = await loadTsconfig(root); | ||
| if (options.experimental.tsconfigPaths !== false && options.typescript.tsConfig.compilerOptions?.paths) options.alias = { | ||
| ...tsConfigToAliasObj(options.typescript.tsConfig, root), | ||
| ...options.alias | ||
| }; | ||
| } | ||
| async function loadTsconfig(root) { | ||
| const opts = { | ||
| root, | ||
| cache: loadTsconfig["__cache"] ??= new TSConfckCache(), | ||
| ignoreNodeModules: true | ||
| }; | ||
| const tsConfigPath = join(root, "tsconfig.json"); | ||
| const parsed = await parse(tsConfigPath, opts).catch(() => void 0); | ||
| if (!parsed) return {}; | ||
| const { tsconfig, tsconfigFile } = parsed; | ||
| tsconfig.compilerOptions ??= {}; | ||
| if (!tsconfig.compilerOptions.baseUrl) tsconfig.compilerOptions.baseUrl = resolve(tsconfigFile, ".."); | ||
| return tsconfig; | ||
| } | ||
| function tsConfigToAliasObj(tsconfig, root) { | ||
| const compilerOptions = tsconfig?.compilerOptions; | ||
| if (!compilerOptions?.paths) return {}; | ||
| const paths = compilerOptions.paths; | ||
| const alias = {}; | ||
| for (const [key, targets] of Object.entries(paths)) { | ||
| let source = key; | ||
| let target = targets?.[0]; | ||
| if (!target) continue; | ||
| if (source.includes("*") || target.includes("*")) { | ||
| source = source.replace(/\/\*$/, ""); | ||
| target = target.replace(/\/\*$/, ""); | ||
| if (source.includes("*") || target.includes("*")) continue; | ||
| } | ||
| if (target.startsWith(".")) { | ||
| if (!compilerOptions.baseUrl) continue; | ||
| target = resolve(root, compilerOptions.baseUrl, target) + (key.endsWith("*") ? "/" : ""); | ||
| } | ||
| alias[source] = target; | ||
| } | ||
| return alias; | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/paths.ts | ||
| const RESOLVE_EXTENSIONS = [ | ||
| ".ts", | ||
| ".js", | ||
| ".mts", | ||
| ".mjs", | ||
| ".tsx", | ||
| ".jsx" | ||
| ]; | ||
| async function resolvePathOptions(options) { | ||
| options.rootDir = resolve(options.rootDir || ".") + "/"; | ||
| options.buildDir = resolve(options.rootDir, options.buildDir || ".") + "/"; | ||
| options.workspaceDir ||= await findWorkspaceDir(options.rootDir).catch(() => options.rootDir) + "/"; | ||
| if (options.srcDir) { | ||
| if (options.serverDir === void 0) options.serverDir = options.srcDir; | ||
| consola$1.warn(`"srcDir" option is deprecated. Please use "serverDir" instead.`); | ||
| } | ||
| if (options.serverDir !== false) { | ||
| if (options.serverDir === true) options.serverDir = "server"; | ||
| options.serverDir = resolve(options.rootDir, options.serverDir || ".") + "/"; | ||
| } | ||
| options.alias ??= {}; | ||
| if (!options.static && !options.entry) throw new Error(`Nitro entry is missing! Is "${options.preset}" preset correct?`); | ||
| if (options.entry) options.entry = resolveNitroPath(options.entry, options); | ||
| options.output.dir = resolveNitroPath(options.output.dir || NitroDefaults.output.dir, options, options.rootDir) + "/"; | ||
| options.output.publicDir = resolveNitroPath(options.output.publicDir || NitroDefaults.output.publicDir, options, options.rootDir) + "/"; | ||
| options.output.serverDir = resolveNitroPath(options.output.serverDir || NitroDefaults.output.serverDir, options, options.rootDir) + "/"; | ||
| options.nodeModulesDirs.push(resolve(options.rootDir, "node_modules")); | ||
| options.nodeModulesDirs.push(resolve(options.workspaceDir, "node_modules")); | ||
| options.nodeModulesDirs.push(resolve(pkgDir, "dist/node_modules")); | ||
| options.nodeModulesDirs.push(resolve(pkgDir, "node_modules")); | ||
| options.nodeModulesDirs.push(resolve(pkgDir, "..")); | ||
| options.nodeModulesDirs = [...new Set(options.nodeModulesDirs.map((dir) => resolve(options.rootDir, dir) + "/"))]; | ||
| options.plugins = options.plugins.map((p) => resolveNitroPath(p, options)); | ||
| if (options.serverDir) options.scanDirs.unshift(options.serverDir); | ||
| options.scanDirs = options.scanDirs.map((dir) => resolve(options.rootDir, dir)); | ||
| options.scanDirs = [...new Set(options.scanDirs.map((dir) => dir + "/"))]; | ||
| options.handlers = options.handlers.map((h) => { | ||
| return { | ||
| ...h, | ||
| handler: resolveNitroPath(h.handler, options) | ||
| }; | ||
| }); | ||
| options.routes = Object.fromEntries(Object.entries(options.routes).map(([route, h]) => { | ||
| if (typeof h === "string") h = { handler: h }; | ||
| h.handler = resolveNitroPath(h.handler, options); | ||
| return [route, h]; | ||
| })); | ||
| if (!options.routes["/**"] && !options.handlers.some((h) => h.route === "/**")) { | ||
| const serverEntry = resolveModulePath("./server", { | ||
| from: [options.rootDir, ...options.scanDirs], | ||
| extensions: RESOLVE_EXTENSIONS, | ||
| try: true | ||
| }); | ||
| if (serverEntry) { | ||
| if (!(options.handlers.some((h) => h.handler === serverEntry) || Object.values(options.routes).some((r) => r.handler === serverEntry))) { | ||
| options.routes["/**"] = { handler: serverEntry }; | ||
| consola$1.info(`Using \`${prettyPath(serverEntry)}\` as default route handler.`); | ||
| } | ||
| } | ||
| } | ||
| if (options.renderer?.handler) options.renderer.handler = resolveModulePath(resolveNitroPath(options.renderer?.handler, options), { | ||
| from: [options.rootDir, ...options.scanDirs], | ||
| extensions: RESOLVE_EXTENSIONS | ||
| }); | ||
| if (options.renderer?.template) options.renderer.template = resolveModulePath(resolveNitroPath(options.renderer?.template, options), { | ||
| from: [options.rootDir, ...options.scanDirs], | ||
| extensions: [".html"] | ||
| }); | ||
| else if (!options.renderer?.handler) { | ||
| const defaultIndex = resolveModulePath("./index.html", { | ||
| from: [options.rootDir, ...options.scanDirs], | ||
| extensions: [".html"], | ||
| try: true | ||
| }); | ||
| if (defaultIndex) { | ||
| options.renderer ??= {}; | ||
| options.renderer.template = defaultIndex; | ||
| consola$1.info(`Using \`${prettyPath(defaultIndex)}\` as renderer template.`); | ||
| } | ||
| } | ||
| if (options.renderer?.template && !options.renderer?.handler) { | ||
| options.renderer ??= {}; | ||
| options.renderer.handler = join(runtimeDir, "internal/routes/renderer-template" + (options.dev ? ".dev" : "")); | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/route-rules.ts | ||
| async function resolveRouteRulesOptions(options) { | ||
| options.routeRules = normalizeRouteRules(options); | ||
| } | ||
| function normalizeRouteRules(config) { | ||
| const normalizedRules = {}; | ||
| for (let path in config.routeRules) { | ||
| const routeConfig = config.routeRules[path]; | ||
| path = withLeadingSlash(path); | ||
| const routeRules = { | ||
| ...routeConfig, | ||
| redirect: void 0, | ||
| proxy: void 0 | ||
| }; | ||
| if (routeConfig.redirect) { | ||
| routeRules.redirect = { | ||
| to: "/", | ||
| status: 307, | ||
| ...typeof routeConfig.redirect === "string" ? { to: routeConfig.redirect } : routeConfig.redirect | ||
| }; | ||
| if (path.endsWith("/**")) routeRules.redirect._redirectStripBase = path.slice(0, -3); | ||
| } | ||
| if (routeConfig.proxy) { | ||
| routeRules.proxy = typeof routeConfig.proxy === "string" ? { to: routeConfig.proxy } : routeConfig.proxy; | ||
| if (path.endsWith("/**")) routeRules.proxy._proxyStripBase = path.slice(0, -3); | ||
| } | ||
| if (routeConfig.cors) routeRules.headers = { | ||
| "access-control-allow-origin": "*", | ||
| "access-control-allow-methods": "*", | ||
| "access-control-allow-headers": "*", | ||
| "access-control-max-age": "0", | ||
| ...routeRules.headers | ||
| }; | ||
| if (routeConfig.swr) { | ||
| routeRules.cache = routeRules.cache || {}; | ||
| routeRules.cache.swr = true; | ||
| if (typeof routeConfig.swr === "number") routeRules.cache.maxAge = routeConfig.swr; | ||
| } | ||
| if (routeConfig.cache === false) routeRules.cache = false; | ||
| normalizedRules[path] = routeRules; | ||
| } | ||
| return normalizedRules; | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/runtime-config.ts | ||
| async function resolveRuntimeConfigOptions(options) { | ||
| options.runtimeConfig = normalizeRuntimeConfig(options); | ||
| } | ||
| function normalizeRuntimeConfig(config) { | ||
| provideFallbackValues(config.runtimeConfig || {}); | ||
| const runtimeConfig = defu(config.runtimeConfig, { | ||
| app: { baseURL: config.baseURL }, | ||
| nitro: { | ||
| envExpansion: config.experimental?.envExpansion, | ||
| openAPI: config.openAPI | ||
| } | ||
| }); | ||
| runtimeConfig.nitro.routeRules = config.routeRules; | ||
| checkSerializableRuntimeConfig(runtimeConfig); | ||
| return runtimeConfig; | ||
| } | ||
| function provideFallbackValues(obj) { | ||
| for (const key in obj) if (obj[key] === void 0 || obj[key] === null) obj[key] = ""; | ||
| else if (typeof obj[key] === "object") provideFallbackValues(obj[key]); | ||
| } | ||
| function checkSerializableRuntimeConfig(obj, path = []) { | ||
| if (isPrimitiveValue(obj)) return; | ||
| for (const key in obj) { | ||
| const value = obj[key]; | ||
| if (value === null || value === void 0 || isPrimitiveValue(value)) continue; | ||
| if (Array.isArray(value)) for (const [index, item] of value.entries()) checkSerializableRuntimeConfig(item, [...path, `${key}[${index}]`]); | ||
| else if (typeof value === "object" && value.constructor === Object && (!value.constructor?.name || value.constructor.name === "Object")) checkSerializableRuntimeConfig(value, [...path, key]); | ||
| else console.warn(`Runtime config option \`${[...path, key].join(".")}\` may not be able to be serialized.`); | ||
| } | ||
| } | ||
| function isPrimitiveValue(value) { | ||
| return typeof value === "string" || typeof value === "number" || typeof value === "boolean"; | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/storage.ts | ||
| async function resolveStorageOptions(options) {} | ||
| //#endregion | ||
| //#region src/config/resolvers/url.ts | ||
| async function resolveURLOptions(options) { | ||
| options.baseURL = withLeadingSlash(withTrailingSlash(options.baseURL)); | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/error.ts | ||
| async function resolveErrorOptions(options) { | ||
| if (!options.errorHandler) options.errorHandler = []; | ||
| else if (!Array.isArray(options.errorHandler)) options.errorHandler = [options.errorHandler]; | ||
| options.errorHandler = options.errorHandler.map((h) => resolveNitroPath(h, options)); | ||
| options.errorHandler.push(join(runtimeDir, `internal/error/${options.dev ? "dev" : "prod"}`)); | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/unenv.ts | ||
| const common = { | ||
| meta: { | ||
| name: "nitro-common", | ||
| url: import.meta.url | ||
| }, | ||
| alias: { | ||
| "buffer/": "node:buffer", | ||
| "buffer/index": "node:buffer", | ||
| "buffer/index.js": "node:buffer", | ||
| "string_decoder/": "node:string_decoder", | ||
| "process/": "node:process" | ||
| } | ||
| }; | ||
| const nodeless = { | ||
| meta: { | ||
| name: "nitro-nodeless", | ||
| url: import.meta.url | ||
| }, | ||
| inject: { | ||
| global: "unenv/polyfill/globalthis", | ||
| process: "node:process", | ||
| Buffer: ["node:buffer", "Buffer"], | ||
| clearImmediate: ["node:timers", "clearImmediate"], | ||
| setImmediate: ["node:timers", "setImmediate"], | ||
| performance: "unenv/polyfill/performance", | ||
| PerformanceObserver: ["node:perf_hooks", "PerformanceObserver"], | ||
| BroadcastChannel: ["node:worker_threads", "BroadcastChannel"] | ||
| }, | ||
| polyfill: [ | ||
| "unenv/polyfill/globalthis-global", | ||
| "unenv/polyfill/process", | ||
| "unenv/polyfill/buffer", | ||
| "unenv/polyfill/timers" | ||
| ] | ||
| }; | ||
| async function resolveUnenv(options) { | ||
| options.unenv ??= []; | ||
| if (!Array.isArray(options.unenv)) options.unenv = [options.unenv]; | ||
| options.unenv = options.unenv.filter(Boolean); | ||
| if (!options.node) options.unenv.unshift(nodeless); | ||
| options.unenv.unshift(common); | ||
| } | ||
| //#endregion | ||
| //#region src/config/resolvers/builder.ts | ||
| const VALID_BUILDERS = [ | ||
| "rollup", | ||
| "rolldown", | ||
| "vite", | ||
| "rolldown-vite" | ||
| ]; | ||
| async function resolveBuilder(options) { | ||
| options.builder ??= process.env.NITRO_BUILDER; | ||
| if (options.builder) { | ||
| if (!VALID_BUILDERS.includes(options.builder)) throw new Error(`Invalid nitro builder "${options.builder}". Valid builders are: ${VALID_BUILDERS.join(", ")}.`); | ||
| const pkg = options.builder === "rolldown-vite" ? "vite" : options.builder; | ||
| if (!isPkgInstalled(pkg, options.rootDir)) { | ||
| if (!await consola$1.prompt(`Nitro builder package \`${pkg}\` is not installed. Would you like to install it?`, { | ||
| type: "confirm", | ||
| default: true, | ||
| cancel: "null" | ||
| })) throw new Error(`Nitro builder package "${options.builder}" is not installed. Please install it in your project dependencies.`); | ||
| await installPkg(pkg, options.rootDir); | ||
| } | ||
| return; | ||
| } | ||
| for (const pkg of [ | ||
| "rolldown", | ||
| "rollup", | ||
| "vite" | ||
| ]) if (isPkgInstalled(pkg, options.rootDir)) { | ||
| options.builder = pkg; | ||
| return; | ||
| } | ||
| const pkgToInstall = await consola$1.prompt(`No nitro builder specified. Which builder would you like to install?`, { | ||
| type: "select", | ||
| cancel: "null", | ||
| options: VALID_BUILDERS.map((b) => ({ | ||
| label: b, | ||
| value: b | ||
| })) | ||
| }); | ||
| if (!pkgToInstall) throw new Error(`No nitro builder specified. Please install one of the following packages: ${VALID_BUILDERS.join(", ")} and set it as the builder in your nitro config or via the NITRO_BUILDER environment variable.`); | ||
| await installPkg(pkgToInstall, options.rootDir); | ||
| options.builder = pkgToInstall; | ||
| } | ||
| const require = createRequire(process.cwd() + "/_index.js"); | ||
| function isPkgInstalled(pkg, root) { | ||
| try { | ||
| require.resolve(pkg, { paths: [root] }); | ||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
| async function installPkg(pkg, root) { | ||
| const { addDevDependency } = await import("../cli/_chunks/dist4.mjs"); | ||
| return addDevDependency(pkg === "rolldown-vite" ? "vite@npm:rolldown-vite" : pkg, { cwd: root }); | ||
| } | ||
| //#endregion | ||
| //#region src/config/loader.ts | ||
| const configResolvers = [ | ||
| resolveCompatibilityOptions, | ||
| resolveTsconfig, | ||
| resolvePathOptions, | ||
| resolveImportsOptions, | ||
| resolveRouteRulesOptions, | ||
| resolveDatabaseOptions, | ||
| resolveExportConditionsOptions, | ||
| resolveRuntimeConfigOptions, | ||
| resolveOpenAPIOptions, | ||
| resolveURLOptions, | ||
| resolveAssetsOptions, | ||
| resolveStorageOptions, | ||
| resolveErrorOptions, | ||
| resolveUnenv, | ||
| resolveBuilder | ||
| ]; | ||
| async function loadOptions(configOverrides = {}, opts = {}) { | ||
| const options = await _loadUserConfig(configOverrides, opts); | ||
| for (const resolver of configResolvers) await resolver(options); | ||
| return options; | ||
| } | ||
| async function _loadUserConfig(configOverrides = {}, opts = {}) { | ||
| configOverrides = klona(configOverrides); | ||
| globalThis.defineNitroConfig = globalThis.defineNitroConfig || ((c) => c); | ||
| let compatibilityDate = configOverrides.compatibilityDate || opts.compatibilityDate || process.env.NITRO_COMPATIBILITY_DATE || process.env.SERVER_COMPATIBILITY_DATE || process.env.COMPATIBILITY_DATE; | ||
| const { resolvePreset } = await import("../_presets.mjs"); | ||
| let preset = configOverrides.preset || process.env.NITRO_PRESET || process.env.SERVER_PRESET; | ||
| const _dotenv = opts.dotenv ?? (configOverrides.dev && { fileName: [".env", ".env.local"] }); | ||
| const loadedConfig = await (opts.watch ? watchConfig : loadConfig)({ | ||
| name: "nitro", | ||
| cwd: configOverrides.rootDir, | ||
| dotenv: _dotenv, | ||
| extend: { extendKey: ["extends", "preset"] }, | ||
| defaults: NitroDefaults, | ||
| jitiOptions: { alias: { | ||
| nitropack: "nitro/config", | ||
| "nitro/config": "nitro/config" | ||
| } }, | ||
| async overrides({ rawConfigs }) { | ||
| const getConf = (key) => configOverrides[key] ?? rawConfigs.main?.[key] ?? rawConfigs.rc?.[key] ?? rawConfigs.packageJson?.[key]; | ||
| if (!compatibilityDate) compatibilityDate = getConf("compatibilityDate"); | ||
| const framework = getConf("framework"); | ||
| const isCustomFramework = framework?.name && framework.name !== "nitro"; | ||
| if (!preset) preset = getConf("preset"); | ||
| if (configOverrides.dev) preset = preset && preset !== "nitro-dev" ? await resolvePreset(preset, { | ||
| static: getConf("static"), | ||
| dev: true, | ||
| compatibilityDate: compatibilityDate || "latest" | ||
| }).then((p) => p?._meta?.name || "nitro-dev").catch(() => "nitro-dev") : "nitro-dev"; | ||
| else if (!preset) preset = await resolvePreset("", { | ||
| static: getConf("static"), | ||
| dev: false, | ||
| compatibilityDate: compatibilityDate || "latest" | ||
| }).then((p) => p?._meta?.name); | ||
| return { | ||
| ...configOverrides, | ||
| preset, | ||
| typescript: { | ||
| generateRuntimeConfigTypes: !isCustomFramework, | ||
| ...getConf("typescript"), | ||
| ...configOverrides.typescript | ||
| } | ||
| }; | ||
| }, | ||
| async resolve(id) { | ||
| const preset$1 = await resolvePreset(id, { | ||
| static: configOverrides.static, | ||
| compatibilityDate: compatibilityDate || "latest", | ||
| dev: configOverrides.dev | ||
| }); | ||
| if (preset$1) return { config: klona(preset$1) }; | ||
| }, | ||
| ...opts.c12 | ||
| }); | ||
| const options = klona(loadedConfig.config); | ||
| options._config = configOverrides; | ||
| options._c12 = loadedConfig; | ||
| options.preset = (loadedConfig.layers || []).find((l) => l.config?._meta?.name)?.config?._meta?.name || preset; | ||
| options.compatibilityDate = resolveCompatibilityDates(compatibilityDate, options.compatibilityDate); | ||
| if (options.dev && options.preset !== "nitro-dev") consola$1.info(`Using \`${options.preset}\` emulation in development mode.`); | ||
| return options; | ||
| } | ||
| //#endregion | ||
| //#region src/config/update.ts | ||
| async function updateNitroConfig(nitro, config) { | ||
| nitro.options.routeRules = normalizeRouteRules(config.routeRules ? config : nitro.options); | ||
| nitro.options.runtimeConfig = normalizeRuntimeConfig(config.runtimeConfig ? config : nitro.options); | ||
| await nitro.hooks.callHook("rollup:reload"); | ||
| consola$1.success("Nitro config hot reloaded!"); | ||
| } | ||
| //#endregion | ||
| //#region src/module.ts | ||
| async function installModules(nitro) { | ||
| const _modules = [...nitro.options.modules || []]; | ||
| const modules = await Promise.all(_modules.map((mod) => _resolveNitroModule(mod, nitro.options))); | ||
| const _installedURLs = /* @__PURE__ */ new Set(); | ||
| for (const mod of modules) { | ||
| if (mod._url) { | ||
| if (_installedURLs.has(mod._url)) continue; | ||
| _installedURLs.add(mod._url); | ||
| } | ||
| await mod.setup(nitro); | ||
| } | ||
| } | ||
| async function _resolveNitroModule(mod, nitroOptions) { | ||
| let _url; | ||
| if (typeof mod === "string") mod = await import(resolveModuleURL(mod, { | ||
| from: [nitroOptions.rootDir], | ||
| extensions: [ | ||
| ".mjs", | ||
| ".cjs", | ||
| ".js", | ||
| ".mts", | ||
| ".cts", | ||
| ".ts" | ||
| ] | ||
| })).then((m) => m.default || m); | ||
| if (typeof mod === "function") mod = { setup: mod }; | ||
| if ("nitro" in mod) mod = mod.nitro; | ||
| if (!mod.setup) throw new Error("Invalid Nitro module: missing setup() function."); | ||
| return { | ||
| _url, | ||
| ...mod | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region src/task.ts | ||
| /** @experimental */ | ||
| async function runTask(taskEvent, opts) { | ||
| return await (await _getTasksContext(opts)).devFetch(`/_nitro/tasks/${taskEvent.name}`, { | ||
| method: "POST", | ||
| body: taskEvent | ||
| }); | ||
| } | ||
| /** @experimental */ | ||
| async function listTasks(opts) { | ||
| return (await (await _getTasksContext(opts)).devFetch("/_nitro/tasks")).tasks; | ||
| } | ||
| function addNitroTasksVirtualFile(nitro) { | ||
| nitro.options.virtual["#nitro-internal-virtual/tasks"] = () => { | ||
| const _scheduledTasks = Object.entries(nitro.options.scheduledTasks || {}).map(([cron, _tasks]) => { | ||
| return { | ||
| cron, | ||
| tasks: (Array.isArray(_tasks) ? _tasks : [_tasks]).filter((name) => { | ||
| if (!nitro.options.tasks[name]) { | ||
| nitro.logger.warn(`Scheduled task \`${name}\` is not defined!`); | ||
| return false; | ||
| } | ||
| return true; | ||
| }) | ||
| }; | ||
| }).filter((e) => e.tasks.length > 0); | ||
| const scheduledTasks = _scheduledTasks.length > 0 ? _scheduledTasks : false; | ||
| return ` | ||
| export const scheduledTasks = ${JSON.stringify(scheduledTasks)}; | ||
| export const tasks = { | ||
| ${Object.entries(nitro.options.tasks).map(([name, task]) => `"${name}": { | ||
| meta: { | ||
| description: ${JSON.stringify(task.description)}, | ||
| }, | ||
| resolve: ${task.handler ? `() => import("${normalize(task.handler)}").then(r => r.default || r)` : "undefined"}, | ||
| }`).join(",\n")} | ||
| };`; | ||
| }; | ||
| } | ||
| const _devHint = `(is dev server running?)`; | ||
| async function _getTasksContext(opts) { | ||
| const buildInfoPath = resolve(resolve(resolve(process.cwd(), opts?.cwd || "."), opts?.buildDir || "node_modules/.nitro"), "nitro.dev.json"); | ||
| if (!existsSync(buildInfoPath)) throw new Error(`Missing info file: \`${buildInfoPath}\` ${_devHint}`); | ||
| const buildInfo = JSON.parse(await readFile(buildInfoPath, "utf8")); | ||
| if (!buildInfo.dev?.pid || !buildInfo.dev?.workerAddress) throw new Error(`Missing dev server info in: \`${buildInfoPath}\` ${_devHint}`); | ||
| if (!_pidIsRunning(buildInfo.dev.pid)) throw new Error(`Dev server is not running (pid: ${buildInfo.dev.pid})`); | ||
| return { | ||
| buildInfo, | ||
| devFetch: ofetch.create({ | ||
| baseURL: `http://${buildInfo.dev.workerAddress.host || "localhost"}:${buildInfo.dev.workerAddress.port || "3000"}`, | ||
| socketPath: buildInfo.dev.workerAddress.socketPath | ||
| }) | ||
| }; | ||
| } | ||
| function _pidIsRunning(pid) { | ||
| try { | ||
| process.kill(pid, 0); | ||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/routing.ts | ||
| const isGlobalMiddleware = (h) => !h.method && (!h.route || h.route === "/**"); | ||
| function initNitroRouting(nitro) { | ||
| const envConditions = new Set([ | ||
| nitro.options.dev ? "dev" : "prod", | ||
| nitro.options.preset, | ||
| nitro.options.preset === "nitro-prerender" ? "prerender" : void 0 | ||
| ].filter(Boolean)); | ||
| const matchesEnv = (h) => { | ||
| const envs = (Array.isArray(h.env) ? h.env : [h.env]).filter(Boolean); | ||
| return envs.length === 0 || envs.some((env) => envConditions.has(env)); | ||
| }; | ||
| const routes = new Router(nitro.options.baseURL); | ||
| const routeRules = new Router(nitro.options.baseURL); | ||
| const globalMiddleware = []; | ||
| const routedMiddleware = new Router(nitro.options.baseURL); | ||
| const sync = () => { | ||
| routeRules._update(Object.entries(nitro.options.routeRules).map(([route, data]) => ({ | ||
| route, | ||
| method: "", | ||
| data: { | ||
| ...data, | ||
| _route: route | ||
| } | ||
| }))); | ||
| const _routes = [ | ||
| ...Object.entries(nitro.options.routes).flatMap(([route, handler]) => { | ||
| if (typeof handler === "string") handler = { handler }; | ||
| return { | ||
| ...handler, | ||
| route, | ||
| middleware: false | ||
| }; | ||
| }), | ||
| ...nitro.options.handlers, | ||
| ...nitro.scannedHandlers | ||
| ].filter((h) => h && !h.middleware && matchesEnv(h)); | ||
| if (nitro.options.renderer?.handler) _routes.push({ | ||
| route: "/**", | ||
| lazy: true, | ||
| handler: nitro.options.renderer?.handler | ||
| }); | ||
| routes._update(_routes.map((h) => ({ | ||
| ...h, | ||
| method: h.method || "", | ||
| data: handlerWithImportHash(h) | ||
| })), { merge: true }); | ||
| const _middleware = [...nitro.scannedHandlers, ...nitro.options.handlers].filter((h) => h && h.middleware && matchesEnv(h)); | ||
| if (nitro.options.serveStatic) _middleware.unshift({ | ||
| route: "/**", | ||
| middleware: true, | ||
| handler: join(runtimeDir, "internal/static") | ||
| }); | ||
| globalMiddleware.splice(0, globalMiddleware.length, ..._middleware.filter((h) => isGlobalMiddleware(h)).map((m) => handlerWithImportHash(m))); | ||
| routedMiddleware._update(_middleware.filter((h) => !isGlobalMiddleware(h)).map((h) => ({ | ||
| ...h, | ||
| method: h.method || "", | ||
| data: handlerWithImportHash(h) | ||
| }))); | ||
| }; | ||
| nitro.routing = Object.freeze({ | ||
| sync, | ||
| routes, | ||
| routeRules, | ||
| globalMiddleware, | ||
| routedMiddleware | ||
| }); | ||
| } | ||
| function handlerWithImportHash(h) { | ||
| const id = (h.lazy ? "_lazy_" : "_") + hash(h.handler).replace(/-/g, "").slice(0, 6); | ||
| return { | ||
| ...h, | ||
| _importHash: id | ||
| }; | ||
| } | ||
| var Router = class { | ||
| _routes; | ||
| _router; | ||
| _compiled; | ||
| _baseURL; | ||
| constructor(baseURL) { | ||
| this._update([]); | ||
| this._baseURL = baseURL || ""; | ||
| if (this._baseURL.endsWith("/")) this._baseURL = this._baseURL.slice(0, -1); | ||
| } | ||
| get routes() { | ||
| return this._routes; | ||
| } | ||
| _update(routes, opts) { | ||
| this._routes = routes; | ||
| this._router = createRouter(); | ||
| this._compiled = void 0; | ||
| for (const route of routes) addRoute(this._router, route.method, this._baseURL + route.route, route.data); | ||
| if (opts?.merge) mergeCatchAll(this._router); | ||
| } | ||
| hasRoutes() { | ||
| return this._routes.length > 0; | ||
| } | ||
| compileToString(opts) { | ||
| if (this._compiled) return this._compiled; | ||
| this._compiled = compileRouterToString(this._router, void 0, opts); | ||
| if (this.routes.length === 1 && this.routes[0].route === "/**" && this.routes[0].method === "") this._compiled = `/* @__PURE__ */ (() => {const data=${(opts?.serialize || JSON.stringify)(this.routes[0].data)};return ((_m, p)=>{return {data,params:{"_":p.slice(1)}};})})()`; | ||
| return this._compiled; | ||
| } | ||
| match(method, path) { | ||
| return findRoute(this._router, method, path)?.data; | ||
| } | ||
| matchAll(method, path) { | ||
| return findAllRoutes(this._router, method, path).map((route) => route.data); | ||
| } | ||
| }; | ||
| function mergeCatchAll(router) { | ||
| const handlers = router.root?.wildcard?.methods?.[""]; | ||
| if (!handlers || handlers.length < 2) return; | ||
| handlers.splice(0, handlers.length, { | ||
| ...handlers[0], | ||
| data: handlers.map((h) => h.data) | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region src/global.ts | ||
| const nitroInstances = globalThis.__nitro_instances__ ||= []; | ||
| const globalKey = "__nitro_builder__"; | ||
| function registerNitroInstance(nitro) { | ||
| if (nitroInstances.includes(nitro)) return; | ||
| globalInit(); | ||
| nitroInstances.unshift(nitro); | ||
| nitro.hooks.hookOnce("close", () => { | ||
| nitroInstances.splice(nitroInstances.indexOf(nitro), 1); | ||
| if (nitroInstances.length === 0) delete globalThis[globalKey]; | ||
| }); | ||
| } | ||
| function globalInit() { | ||
| if (globalThis[globalKey]) return; | ||
| globalThis[globalKey] = { async fetch(req) { | ||
| for (let r = 0; r < 10 && nitroInstances.length === 0; r++) await new Promise((resolve$1) => setTimeout(resolve$1, 300)); | ||
| const nitro = nitroInstances[0]; | ||
| if (!nitro) throw new Error("No Nitro instance is running."); | ||
| return nitro.fetch(req); | ||
| } }; | ||
| } | ||
| //#endregion | ||
| //#region src/nitro.ts | ||
| async function createNitro(config = {}, opts = {}) { | ||
| const nitro = { | ||
| options: await loadOptions(config, opts), | ||
| hooks: new Hookable(), | ||
| vfs: {}, | ||
| routing: {}, | ||
| logger: consola.withTag("nitro"), | ||
| scannedHandlers: [], | ||
| fetch: () => { | ||
| throw new Error("no dev server attached!"); | ||
| }, | ||
| close: () => Promise.resolve(nitro.hooks.callHook("close")), | ||
| async updateConfig(config$1) { | ||
| updateNitroConfig(nitro, config$1); | ||
| } | ||
| }; | ||
| registerNitroInstance(nitro); | ||
| initNitroRouting(nitro); | ||
| await scanAndSyncOptions(nitro); | ||
| if (nitro.options.debug) createDebugger(nitro.hooks, { tag: "nitro" }); | ||
| if (nitro.options.logLevel !== void 0) nitro.logger.level = nitro.options.logLevel; | ||
| nitro.hooks.addHooks(nitro.options.hooks); | ||
| addNitroTasksVirtualFile(nitro); | ||
| await installModules(nitro); | ||
| if (nitro.options.imports) { | ||
| nitro.unimport = createUnimport(nitro.options.imports); | ||
| await nitro.unimport.init(); | ||
| nitro.options.virtual["#imports"] = () => nitro.unimport?.toExports() || ""; | ||
| nitro.options.virtual["#nitro"] = "export * from \"#imports\""; | ||
| } | ||
| await scanHandlers(nitro); | ||
| nitro.routing.sync(); | ||
| return nitro; | ||
| } | ||
| //#endregion | ||
| //#region src/build/build.ts | ||
| async function build(nitro) { | ||
| switch (nitro.options.builder) { | ||
| case "rollup": { | ||
| const { rollupBuild } = await import("../_build/rollup.mjs"); | ||
| return rollupBuild(nitro); | ||
| } | ||
| case "rolldown": { | ||
| const { rolldownBuild } = await import("../_build/rolldown.mjs"); | ||
| return rolldownBuild(nitro); | ||
| } | ||
| case "vite": | ||
| case "rolldown-vite": { | ||
| const { viteBuild } = await import("../_build/vite.build.mjs"); | ||
| return viteBuild(nitro); | ||
| } | ||
| default: throw new Error(`Unknown builder: ${nitro.options.builder}`); | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region src/utils/compress.ts | ||
| async function compressPublicAssets(nitro) { | ||
| const publicFiles = await glob("**", { | ||
| cwd: nitro.options.output.publicDir, | ||
| absolute: false, | ||
| dot: true, | ||
| ignore: ["**/*.gz", "**/*.br"] | ||
| }); | ||
| await Promise.all(publicFiles.map(async (fileName) => { | ||
| const filePath = resolve(nitro.options.output.publicDir, fileName); | ||
| if (existsSync(filePath + ".gz") || existsSync(filePath + ".br")) return; | ||
| const mimeType = src_default.getType(fileName) || "text/plain"; | ||
| const fileContents = await fsp.readFile(filePath); | ||
| if (fileContents.length < 1024 || fileName.endsWith(".map") || !isCompressibleMime(mimeType)) return; | ||
| const { gzip, brotli } = nitro.options.compressPublicAssets || {}; | ||
| const encodings = [gzip !== false && "gzip", brotli !== false && "br"].filter(Boolean); | ||
| await Promise.all(encodings.map(async (encoding) => { | ||
| const compressedPath = filePath + ("." + (encoding === "gzip" ? "gz" : "br")); | ||
| if (existsSync(compressedPath)) return; | ||
| const gzipOptions = { level: zlib.constants.Z_BEST_COMPRESSION }; | ||
| const brotliOptions = { | ||
| [zlib.constants.BROTLI_PARAM_MODE]: isTextMime(mimeType) ? zlib.constants.BROTLI_MODE_TEXT : zlib.constants.BROTLI_MODE_GENERIC, | ||
| [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY, | ||
| [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fileContents.length | ||
| }; | ||
| const compressedBuff = await new Promise((resolve$1, reject) => { | ||
| const cb = (error, result) => error ? reject(error) : resolve$1(result); | ||
| if (encoding === "gzip") zlib.gzip(fileContents, gzipOptions, cb); | ||
| else zlib.brotliCompress(fileContents, brotliOptions, cb); | ||
| }); | ||
| await fsp.writeFile(compressedPath, compressedBuff); | ||
| })); | ||
| })); | ||
| } | ||
| function isTextMime(mimeType) { | ||
| return /text|javascript|json|xml/.test(mimeType); | ||
| } | ||
| const COMPRESSIBLE_MIMES_RE = new Set([ | ||
| "application/dash+xml", | ||
| "application/eot", | ||
| "application/font", | ||
| "application/font-sfnt", | ||
| "application/javascript", | ||
| "application/json", | ||
| "application/opentype", | ||
| "application/otf", | ||
| "application/pdf", | ||
| "application/pkcs7-mime", | ||
| "application/protobuf", | ||
| "application/rss+xml", | ||
| "application/truetype", | ||
| "application/ttf", | ||
| "application/vnd.apple.mpegurl", | ||
| "application/vnd.mapbox-vector-tile", | ||
| "application/vnd.ms-fontobject", | ||
| "application/wasm", | ||
| "application/xhtml+xml", | ||
| "application/xml", | ||
| "application/x-font-opentype", | ||
| "application/x-font-truetype", | ||
| "application/x-font-ttf", | ||
| "application/x-httpd-cgi", | ||
| "application/x-javascript", | ||
| "application/x-mpegurl", | ||
| "application/x-opentype", | ||
| "application/x-otf", | ||
| "application/x-perl", | ||
| "application/x-ttf", | ||
| "font/eot", | ||
| "font/opentype", | ||
| "font/otf", | ||
| "font/ttf", | ||
| "image/svg+xml", | ||
| "text/css", | ||
| "text/csv", | ||
| "text/html", | ||
| "text/javascript", | ||
| "text/js", | ||
| "text/plain", | ||
| "text/richtext", | ||
| "text/tab-separated-values", | ||
| "text/xml", | ||
| "text/x-component", | ||
| "text/x-java-source", | ||
| "text/x-script", | ||
| "vnd.apple.mpegurl" | ||
| ]); | ||
| function isCompressibleMime(mimeType) { | ||
| return COMPRESSIBLE_MIMES_RE.has(mimeType); | ||
| } | ||
| //#endregion | ||
| //#region src/build/assets.ts | ||
| const NEGATION_RE = /^(!?)(.*)$/; | ||
| const PARENT_DIR_GLOB_RE = /!?\.\.\//; | ||
| async function scanUnprefixedPublicAssets(nitro) { | ||
| const scannedPaths = []; | ||
| for (const asset of nitro.options.publicAssets) { | ||
| if (asset.baseURL && asset.baseURL !== "/" && !asset.fallthrough) continue; | ||
| if (!await isDirectory(asset.dir)) continue; | ||
| const publicAssets = await glob(getIncludePatterns(nitro, asset.dir), { | ||
| cwd: asset.dir, | ||
| absolute: false, | ||
| dot: true | ||
| }); | ||
| scannedPaths.push(...publicAssets.map((file) => join(asset.baseURL || "/", file))); | ||
| } | ||
| return scannedPaths; | ||
| } | ||
| async function copyPublicAssets(nitro) { | ||
| if (nitro.options.noPublicDir) return; | ||
| for (const asset of nitro.options.publicAssets) { | ||
| const assetDir = asset.dir; | ||
| const dstDir = join(nitro.options.output.publicDir, asset.baseURL); | ||
| if (await isDirectory(assetDir)) { | ||
| const publicAssets = await glob(getIncludePatterns(nitro, assetDir), { | ||
| cwd: assetDir, | ||
| absolute: false, | ||
| dot: true | ||
| }); | ||
| await Promise.all(publicAssets.map(async (file) => { | ||
| const src = join(assetDir, file); | ||
| const dst = join(dstDir, file); | ||
| if (!existsSync(dst)) await promises.cp(src, dst); | ||
| })); | ||
| } | ||
| } | ||
| if (nitro.options.compressPublicAssets) await compressPublicAssets(nitro); | ||
| nitro.logger.success("Generated public " + prettyPath(nitro.options.output.publicDir)); | ||
| } | ||
| function getIncludePatterns(nitro, assetDir) { | ||
| return ["**", ...nitro.options.ignore.map((p) => { | ||
| const [_, negation, pattern] = p.match(NEGATION_RE) || []; | ||
| return (negation ? "" : "!") + (pattern.startsWith("*") ? pattern : relative(assetDir, resolve(nitro.options.rootDir, pattern))); | ||
| })].filter((p) => !PARENT_DIR_GLOB_RE.test(p)); | ||
| } | ||
| //#endregion | ||
| //#region src/build/prepare.ts | ||
| async function prepare(nitro) { | ||
| await prepareDir(nitro.options.output.dir); | ||
| if (!nitro.options.noPublicDir) await prepareDir(nitro.options.output.publicDir); | ||
| if (!nitro.options.static) await prepareDir(nitro.options.output.serverDir); | ||
| } | ||
| async function prepareDir(dir) { | ||
| await fsp.rm(dir, { | ||
| recursive: true, | ||
| force: true | ||
| }); | ||
| await fsp.mkdir(dir, { recursive: true }); | ||
| } | ||
| //#endregion | ||
| //#region src/prerender/utils.ts | ||
| const allowedExtensions = new Set(["", ".json"]); | ||
| const linkParents = /* @__PURE__ */ new Map(); | ||
| const HTML_ENTITIES = { | ||
| "<": "<", | ||
| ">": ">", | ||
| "&": "&", | ||
| "'": "'", | ||
| """: "\"" | ||
| }; | ||
| function escapeHtml(text) { | ||
| return text.replace(/&(lt|gt|amp|apos|quot);/g, (ch) => HTML_ENTITIES[ch] || ch); | ||
| } | ||
| async function extractLinks(html, from, res, crawlLinks) { | ||
| const links = []; | ||
| const _links = []; | ||
| if (crawlLinks) await z(P(html), (node) => { | ||
| if (!node.attributes?.href) return; | ||
| const link = escapeHtml(node.attributes.href); | ||
| if (!decodeURIComponent(link).startsWith("#") && allowedExtensions.has(getExtension(link))) _links.push(link); | ||
| }); | ||
| const header = res.headers.get("x-nitro-prerender") || ""; | ||
| _links.push(...header.split(",").map((i) => decodeURIComponent(i.trim()))); | ||
| for (const link of _links.filter(Boolean)) { | ||
| const _link = parseURL(link); | ||
| if (_link.protocol || _link.host) continue; | ||
| if (!_link.pathname.startsWith("/")) { | ||
| const fromURL = new URL(from, "http://localhost"); | ||
| _link.pathname = new URL(_link.pathname, fromURL).pathname; | ||
| } | ||
| links.push(_link.pathname + _link.search); | ||
| } | ||
| for (const link of links) { | ||
| const _parents = linkParents.get(link); | ||
| if (_parents) _parents.add(from); | ||
| else linkParents.set(link, new Set([from])); | ||
| } | ||
| return links; | ||
| } | ||
| const EXT_REGEX = /\.[\da-z]+$/; | ||
| function getExtension(link) { | ||
| return (parseURL(link).pathname.match(EXT_REGEX) || [])[0] || ""; | ||
| } | ||
| function formatPrerenderRoute(route) { | ||
| let str = ` ├─ ${route.route} (${route.generateTimeMS}ms)`; | ||
| if (route.error) { | ||
| const parents = linkParents.get(route.route); | ||
| const errorColor = colors[route.error.status === 404 ? "yellow" : "red"]; | ||
| const errorLead = parents?.size ? "├──" : "└──"; | ||
| str += `\n │ ${errorLead} ${errorColor(route.error.message)}`; | ||
| if (parents?.size) str += `\n${[...parents.values()].map((link) => ` │ └── Linked from ${link}`).join("\n")}`; | ||
| } | ||
| if (route.skip) str += colors.gray(" (skipped)"); | ||
| return colors.gray(str); | ||
| } | ||
| function matchesIgnorePattern(path, pattern) { | ||
| if (typeof pattern === "string") return path.startsWith(pattern); | ||
| if (typeof pattern === "function") return pattern(path) === true; | ||
| if (pattern instanceof RegExp) return pattern.test(path); | ||
| return false; | ||
| } | ||
| //#endregion | ||
| //#region src/prerender/prerender.ts | ||
| const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/; | ||
| async function prerender(nitro) { | ||
| if (nitro.options.noPublicDir) { | ||
| nitro.logger.warn("Skipping prerender since `noPublicDir` option is enabled."); | ||
| return; | ||
| } | ||
| if (nitro.options.builder === "vite") { | ||
| nitro.logger.warn("Skipping prerender since not supported with vite builder yet..."); | ||
| return; | ||
| } | ||
| const routes = new Set(nitro.options.prerender.routes); | ||
| const prerenderRulePaths = Object.entries(nitro.options.routeRules).filter(([path$1, options]) => options.prerender && !path$1.includes("*")).map((e) => e[0]); | ||
| for (const route of prerenderRulePaths) routes.add(route); | ||
| await nitro.hooks.callHook("prerender:routes", routes); | ||
| if (routes.size === 0) if (nitro.options.prerender.crawlLinks) routes.add("/"); | ||
| else return; | ||
| nitro.logger.info("Initializing prerenderer"); | ||
| nitro._prerenderedRoutes = []; | ||
| nitro._prerenderMeta = nitro._prerenderMeta || {}; | ||
| const prerendererConfig = { | ||
| ...nitro.options._config, | ||
| static: false, | ||
| rootDir: nitro.options.rootDir, | ||
| logLevel: 0, | ||
| preset: "nitro-prerender" | ||
| }; | ||
| await nitro.hooks.callHook("prerender:config", prerendererConfig); | ||
| const nitroRenderer = await createNitro(prerendererConfig); | ||
| const prerenderStartTime = Date.now(); | ||
| await nitro.hooks.callHook("prerender:init", nitroRenderer); | ||
| let path = relative(nitro.options.output.dir, nitro.options.output.publicDir); | ||
| if (!path.startsWith(".")) path = `./${path}`; | ||
| nitroRenderer.options.commands.preview = `npx serve ${path}`; | ||
| nitroRenderer.options.output.dir = nitro.options.output.dir; | ||
| await build(nitroRenderer); | ||
| const serverFilename = typeof nitroRenderer.options.rollupConfig?.output?.entryFileNames === "string" ? nitroRenderer.options.rollupConfig.output.entryFileNames : "index.mjs"; | ||
| const prerenderer = await import(pathToFileURL(resolve(nitroRenderer.options.output.serverDir, serverFilename)).href).then((m) => m.default); | ||
| const routeRules = createRouter(); | ||
| for (const [route, rules] of Object.entries(nitro.options.routeRules)) addRoute(routeRules, void 0, route, rules); | ||
| const _getRouteRules = (path$1) => defu({}, ...findAllRoutes(routeRules, void 0, path$1).map((r) => r.data).reverse()); | ||
| const generatedRoutes = /* @__PURE__ */ new Set(); | ||
| const failedRoutes = /* @__PURE__ */ new Set(); | ||
| const skippedRoutes = /* @__PURE__ */ new Set(); | ||
| const displayedLengthWarns = /* @__PURE__ */ new Set(); | ||
| const publicAssetBases = nitro.options.publicAssets.filter((a$1) => !!a$1.baseURL && a$1.baseURL !== "/" && !a$1.fallthrough).map((a$1) => withTrailingSlash(a$1.baseURL)); | ||
| const scannedPublicAssets = nitro.options.prerender.ignoreUnprefixedPublicAssets ? new Set(await scanUnprefixedPublicAssets(nitro)) : /* @__PURE__ */ new Set(); | ||
| const canPrerender = (route = "/") => { | ||
| if (generatedRoutes.has(route) || skippedRoutes.has(route)) return false; | ||
| for (const pattern of nitro.options.prerender.ignore) if (matchesIgnorePattern(route, pattern)) return false; | ||
| if (publicAssetBases.some((base) => route.startsWith(base))) return false; | ||
| if (scannedPublicAssets.has(route)) return false; | ||
| if (_getRouteRules(route).prerender === false) return false; | ||
| return true; | ||
| }; | ||
| const canWriteToDisk = (route) => { | ||
| if (route.route.includes("?")) return false; | ||
| const FS_MAX_SEGMENT = 255; | ||
| const FS_MAX_PATH_PUBLIC_HTML = 1024 - (nitro.options.output.publicDir.length + 10); | ||
| if ((route.route.length >= FS_MAX_PATH_PUBLIC_HTML || route.route.split("/").some((s) => s.length > FS_MAX_SEGMENT)) && !displayedLengthWarns.has(route)) { | ||
| displayedLengthWarns.add(route); | ||
| const _route = route.route.slice(0, 60) + "..."; | ||
| if (route.route.length >= FS_MAX_PATH_PUBLIC_HTML) nitro.logger.warn(`Prerendering long route "${_route}" (${route.route.length}) can cause filesystem issues since it exceeds ${FS_MAX_PATH_PUBLIC_HTML}-character limit when writing to \`${nitro.options.output.publicDir}\`.`); | ||
| else { | ||
| nitro.logger.warn(`Skipping prerender of the route "${_route}" since it exceeds the ${FS_MAX_SEGMENT}-character limit in one of the path segments and can cause filesystem issues.`); | ||
| return false; | ||
| } | ||
| } | ||
| return true; | ||
| }; | ||
| const generateRoute = async (route) => { | ||
| const start = Date.now(); | ||
| route = decodeURI(route); | ||
| if (!canPrerender(route)) { | ||
| skippedRoutes.add(route); | ||
| return; | ||
| } | ||
| generatedRoutes.add(route); | ||
| const _route = { route }; | ||
| const encodedRoute = encodeURI(route); | ||
| const req = toRequest(withBase(encodedRoute, nitro.options.baseURL), { headers: [["x-nitro-prerender", encodedRoute]] }); | ||
| const res = await prerenderer.fetch(req); | ||
| let dataBuff = Buffer.from(await res.arrayBuffer()); | ||
| Object.defineProperty(_route, "contents", { | ||
| get: () => { | ||
| return dataBuff ? dataBuff.toString("utf8") : void 0; | ||
| }, | ||
| set(value) { | ||
| if (dataBuff) dataBuff = Buffer.from(value); | ||
| } | ||
| }); | ||
| Object.defineProperty(_route, "data", { | ||
| get: () => { | ||
| return dataBuff ? dataBuff.buffer : void 0; | ||
| }, | ||
| set(value) { | ||
| if (dataBuff) dataBuff = Buffer.from(value); | ||
| } | ||
| }); | ||
| if (![200, ...[ | ||
| 301, | ||
| 302, | ||
| 303, | ||
| 304, | ||
| 307, | ||
| 308 | ||
| ]].includes(res.status)) { | ||
| _route.error = /* @__PURE__ */ new Error(`[${res.status}] ${res.statusText}`); | ||
| _route.error.status = res.status; | ||
| _route.error.statusText = res.statusText; | ||
| } | ||
| _route.generateTimeMS = Date.now() - start; | ||
| const contentType = res.headers.get("content-type") || ""; | ||
| const isImplicitHTML = !route.endsWith(".html") && contentType.includes("html") && !JsonSigRx.test(dataBuff.subarray(0, 32).toString("utf8")); | ||
| const routeWithIndex = route.endsWith("/") ? route + "index" : route; | ||
| const htmlPath = route.endsWith("/") || nitro.options.prerender.autoSubfolderIndex ? joinURL(route, "index.html") : route + ".html"; | ||
| _route.fileName = withoutBase(isImplicitHTML ? htmlPath : routeWithIndex, nitro.options.baseURL); | ||
| const inferredContentType = src_default.getType(_route.fileName) || "text/plain"; | ||
| _route.contentType = contentType || inferredContentType; | ||
| await nitro.hooks.callHook("prerender:generate", _route, nitro); | ||
| if (_route.contentType !== inferredContentType) { | ||
| nitro._prerenderMeta[_route.fileName] ||= {}; | ||
| nitro._prerenderMeta[_route.fileName].contentType = _route.contentType; | ||
| } | ||
| if (_route.error) failedRoutes.add(_route); | ||
| if (_route.skip || _route.error) { | ||
| await nitro.hooks.callHook("prerender:route", _route); | ||
| nitro.logger.log(formatPrerenderRoute(_route)); | ||
| dataBuff = void 0; | ||
| return _route; | ||
| } | ||
| if (canWriteToDisk(_route)) { | ||
| await writeFile$1(join(nitro.options.output.publicDir, _route.fileName), dataBuff); | ||
| nitro._prerenderedRoutes.push(_route); | ||
| } else _route.skip = true; | ||
| if (!_route.error && (isImplicitHTML || route.endsWith(".html"))) { | ||
| const extractedLinks = await extractLinks(dataBuff.toString("utf8"), route, res, nitro.options.prerender.crawlLinks); | ||
| for (const _link of extractedLinks) if (canPrerender(_link)) routes.add(_link); | ||
| } | ||
| await nitro.hooks.callHook("prerender:route", _route); | ||
| nitro.logger.log(formatPrerenderRoute(_route)); | ||
| dataBuff = void 0; | ||
| return _route; | ||
| }; | ||
| nitro.logger.info(nitro.options.prerender.crawlLinks ? `Prerendering ${routes.size} initial routes with crawler` : `Prerendering ${routes.size} routes`); | ||
| await runParallel(routes, generateRoute, { | ||
| concurrency: nitro.options.prerender.concurrency, | ||
| interval: nitro.options.prerender.interval | ||
| }); | ||
| await prerenderer.close(); | ||
| await nitro.hooks.callHook("prerender:done", { | ||
| prerenderedRoutes: nitro._prerenderedRoutes, | ||
| failedRoutes: [...failedRoutes] | ||
| }); | ||
| if (nitro.options.prerender.failOnError && failedRoutes.size > 0) { | ||
| nitro.logger.log("\nErrors prerendering:"); | ||
| for (const route of failedRoutes) nitro.logger.log(formatPrerenderRoute(route)); | ||
| nitro.logger.log(""); | ||
| throw new Error("Exiting due to prerender errors."); | ||
| } | ||
| const prerenderTimeInMs = Date.now() - prerenderStartTime; | ||
| nitro.logger.info(`Prerendered ${nitro._prerenderedRoutes.length} routes in ${prerenderTimeInMs / 1e3} seconds`); | ||
| if (nitro.options.compressPublicAssets) await compressPublicAssets(nitro); | ||
| } | ||
| //#endregion | ||
| export { createNitro as a, loadOptions as c, build as i, prepare as n, listTasks as o, copyPublicAssets as r, runTask as s, prerender as t }; |
| import { createRequire } from "node:module"; | ||
| //#region rolldown:runtime | ||
| var __create = Object.create; | ||
| var __defProp = Object.defineProperty; | ||
| var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
| var __getOwnPropNames = Object.getOwnPropertyNames; | ||
| var __getProtoOf = Object.getPrototypeOf; | ||
| var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
| var __commonJS = (cb, mod) => function() { | ||
| return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; | ||
| }; | ||
| var __copyProps = (to, from, except, desc) => { | ||
| if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { | ||
| key = keys[i]; | ||
| if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { | ||
| get: ((k) => from[k]).bind(null, key), | ||
| enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable | ||
| }); | ||
| } | ||
| return to; | ||
| }; | ||
| var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { | ||
| value: mod, | ||
| enumerable: true | ||
| }) : target, mod)); | ||
| var __toDynamicImportESM = (isNodeMode) => (mod) => __toESM(mod.default, isNodeMode); | ||
| var __require = /* @__PURE__ */ createRequire(import.meta.url); | ||
| //#endregion | ||
| export { __toESM as i, __require as n, __toDynamicImportESM as r, __commonJS as t }; |
| import { O as relative, k as resolve, x as dirname } from "../_libs/c12.mjs"; | ||
| import { t as glob } from "../_libs/tinyglobby.mjs"; | ||
| import { r as a } from "../_libs/std-env.mjs"; | ||
| import { t as runParallel } from "./ANM1K1bE.mjs"; | ||
| import { t as gzipSize } from "../_libs/gzip-size.mjs"; | ||
| import { t as prettyBytes } from "../_libs/pretty-bytes.mjs"; | ||
| import { promises } from "node:fs"; | ||
| import { colors } from "consola/utils"; | ||
| //#region src/utils/fs-tree.ts | ||
| async function generateFSTree(dir, options = {}) { | ||
| if (a) return; | ||
| const files = await glob("**/*.*", { | ||
| cwd: dir, | ||
| ignore: ["*.map"] | ||
| }); | ||
| const items = []; | ||
| await runParallel(new Set(files), async (file) => { | ||
| const path = resolve(dir, file); | ||
| const src = await promises.readFile(path); | ||
| const size = src.byteLength; | ||
| const gzip = options.compressedSizes ? await gzipSize(src) : 0; | ||
| items.push({ | ||
| file, | ||
| path, | ||
| size, | ||
| gzip | ||
| }); | ||
| }, { concurrency: 10 }); | ||
| items.sort((a$1, b) => a$1.path.localeCompare(b.path)); | ||
| let totalSize = 0; | ||
| let totalGzip = 0; | ||
| let totalNodeModulesSize = 0; | ||
| let totalNodeModulesGzip = 0; | ||
| let treeText = ""; | ||
| for (const [index, item] of items.entries()) { | ||
| let dir$1 = dirname(item.file); | ||
| if (dir$1 === ".") dir$1 = ""; | ||
| const rpath = relative(process.cwd(), item.path); | ||
| const treeChar = index === items.length - 1 ? "└─" : "├─"; | ||
| if (item.file.includes("node_modules")) { | ||
| totalNodeModulesSize += item.size; | ||
| totalNodeModulesGzip += item.gzip; | ||
| continue; | ||
| } | ||
| treeText += colors.gray(` ${treeChar} ${rpath} (${prettyBytes(item.size)})`); | ||
| if (options.compressedSizes) treeText += colors.gray(` (${prettyBytes(item.gzip)} gzip)`); | ||
| treeText += "\n"; | ||
| totalSize += item.size; | ||
| totalGzip += item.gzip; | ||
| } | ||
| treeText += `${colors.cyan("Σ Total size:")} ${prettyBytes(totalSize + totalNodeModulesSize)}`; | ||
| if (options.compressedSizes) treeText += ` (${prettyBytes(totalGzip + totalNodeModulesGzip)} gzip)`; | ||
| treeText += "\n"; | ||
| return treeText; | ||
| } | ||
| //#endregion | ||
| export { generateFSTree as t }; |
| import { O as relative, k as resolve, x as dirname } from "../_libs/c12.mjs"; | ||
| import { t as getProperty } from "../_libs/dot-prop.mjs"; | ||
| import consola$1 from "consola"; | ||
| import { mkdir, stat, writeFile } from "node:fs/promises"; | ||
| import { colors } from "consola/utils"; | ||
| //#region src/utils/fs.ts | ||
| function prettyPath(p, highlight = true) { | ||
| p = relative(process.cwd(), p); | ||
| return highlight ? colors.cyan(p) : p; | ||
| } | ||
| function resolveNitroPath(path, nitroOptions, base) { | ||
| if (typeof path !== "string") throw new TypeError("Invalid path: " + path); | ||
| path = _compilePathTemplate(path)(nitroOptions); | ||
| for (const base$1 in nitroOptions.alias) if (path.startsWith(base$1)) path = nitroOptions.alias[base$1] + path.slice(base$1.length); | ||
| return resolve(base || nitroOptions.rootDir, path); | ||
| } | ||
| function _compilePathTemplate(contents) { | ||
| return (params) => contents.replace(/{{ ?([\w.]+) ?}}/g, (_, match) => { | ||
| const val = getProperty(params, match); | ||
| if (!val) consola$1.warn(`cannot resolve template param '${match}' in ${contents.slice(0, 20)}`); | ||
| return val || `${match}`; | ||
| }); | ||
| } | ||
| async function writeFile$1(file, contents, log = false) { | ||
| await mkdir(dirname(file), { recursive: true }); | ||
| await writeFile(file, contents, typeof contents === "string" ? "utf8" : void 0); | ||
| if (log) consola$1.info("Generated", prettyPath(file)); | ||
| } | ||
| async function isDirectory(path) { | ||
| try { | ||
| return (await stat(path)).isDirectory(); | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
| //#endregion | ||
| export { writeFile$1 as i, prettyPath as n, resolveNitroPath as r, isDirectory as t }; |
-705
| import { S as extname$1, k as resolve$1, n as debounce, w as join$1 } from "./_libs/c12.mjs"; | ||
| import { n as T, r as a } from "./_libs/std-env.mjs"; | ||
| import { t as src_default } from "./_libs/mime.mjs"; | ||
| import { r as writeDevBuildInfo } from "./_build/common.mjs"; | ||
| import { n as createProxyServer } from "./_libs/httpxy.mjs"; | ||
| import { i as watch$1 } from "./_libs/chokidar.mjs"; | ||
| import consola$1 from "consola"; | ||
| import { dirname, resolve } from "node:path"; | ||
| import { createReadStream, existsSync } from "node:fs"; | ||
| import { joinURL } from "ufo"; | ||
| import { readFile, rm, stat } from "node:fs/promises"; | ||
| import { createBrotliCompress, createGzip } from "node:zlib"; | ||
| import { Worker } from "node:worker_threads"; | ||
| import { H3, HTTPError, defineHandler, fromNodeHandler, getRequestIP, getRequestURL, serveStatic, toEventHandler } from "h3"; | ||
| import { Agent } from "undici"; | ||
| import { serve } from "srvx/node"; | ||
| import { ErrorParser } from "youch-core"; | ||
| import { Youch } from "youch"; | ||
| import { SourceMapConsumer } from "source-map"; | ||
| import { FastResponse } from "srvx"; | ||
| //#region src/dev/proxy.ts | ||
| function createHTTPProxy(defaults = {}) { | ||
| const proxy = createProxyServer(defaults); | ||
| proxy.on("proxyReq", (proxyReq, req) => { | ||
| if (!proxyReq.hasHeader("x-forwarded-for")) { | ||
| const address = req.socket.remoteAddress; | ||
| if (address) proxyReq.appendHeader("x-forwarded-for", address); | ||
| } | ||
| if (!proxyReq.hasHeader("x-forwarded-port")) { | ||
| if (req?.socket?.localPort) proxyReq.setHeader("x-forwarded-port", req.socket.localPort); | ||
| } | ||
| if (!proxyReq.hasHeader("x-forwarded-Proto")) { | ||
| const encrypted = (req?.connection)?.encrypted; | ||
| proxyReq.setHeader("x-forwarded-proto", encrypted ? "https" : "http"); | ||
| } | ||
| }); | ||
| return { | ||
| proxy, | ||
| async handleEvent(event, opts) { | ||
| try { | ||
| return await fromNodeHandler((req, res) => proxy.web(req, res, opts))(event); | ||
| } catch (error) { | ||
| event.res.headers.set("refresh", "3"); | ||
| throw new HTTPError({ | ||
| status: 503, | ||
| message: "Dev server is unavailable.", | ||
| cause: error | ||
| }); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function fetchAddress(addr, input, inputInit) { | ||
| let url; | ||
| let init; | ||
| if (input instanceof Request) { | ||
| url = new URL(input.url); | ||
| init = { | ||
| method: input.method, | ||
| headers: input.headers, | ||
| body: input.body, | ||
| ...inputInit | ||
| }; | ||
| } else { | ||
| url = new URL(input); | ||
| init = inputInit; | ||
| } | ||
| init = { | ||
| duplex: "half", | ||
| redirect: "manual", | ||
| ...init | ||
| }; | ||
| if (addr.socketPath) { | ||
| url.protocol = "http:"; | ||
| return fetch(url, { | ||
| ...init, | ||
| ...fetchSocketOptions(addr.socketPath) | ||
| }); | ||
| } | ||
| const origin = `http://${addr.host}${addr.port ? `:${addr.port}` : ""}`; | ||
| const outURL = new URL(url.pathname + url.search, origin); | ||
| return fetch(outURL, init); | ||
| } | ||
| function fetchSocketOptions(socketPath) { | ||
| if ("Bun" in globalThis) return { unix: socketPath }; | ||
| if ("Deno" in globalThis) return { client: Deno.createHttpClient({ | ||
| transport: "unix", | ||
| path: socketPath | ||
| }) }; | ||
| return { dispatcher: new Agent({ connect: { socketPath } }) }; | ||
| } | ||
| //#endregion | ||
| //#region src/dev/worker.ts | ||
| var NodeDevWorker = class { | ||
| closed = false; | ||
| #name; | ||
| #entry; | ||
| #data; | ||
| #hooks; | ||
| #worker; | ||
| #address; | ||
| #proxy; | ||
| #messageListeners; | ||
| constructor(opts) { | ||
| this.#name = opts.name; | ||
| this.#entry = opts.entry; | ||
| this.#data = opts.data; | ||
| this.#hooks = opts.hooks; | ||
| this.#proxy = createHTTPProxy(); | ||
| this.#messageListeners = /* @__PURE__ */ new Set(); | ||
| this.#initWorker(); | ||
| } | ||
| get ready() { | ||
| return Boolean(!this.closed && this.#address && this.#proxy && this.#worker); | ||
| } | ||
| async fetch(input, init) { | ||
| for (let i = 0; i < 5 && !(this.#address && this.#proxy); i++) await new Promise((r) => setTimeout(r, 100 * Math.pow(2, i))); | ||
| if (!(this.#address && this.#proxy)) return new Response("Dev worker is unavailable", { status: 503 }); | ||
| return fetchAddress(this.#address, input, init); | ||
| } | ||
| upgrade(req, socket, head) { | ||
| if (!this.ready) return; | ||
| return this.#proxy.proxy.ws(req, socket, { | ||
| target: this.#address, | ||
| xfwd: true | ||
| }, head).catch((error) => { | ||
| consola$1.error("WebSocket proxy error:", error); | ||
| }); | ||
| } | ||
| sendMessage(message) { | ||
| if (!this.#worker) throw new Error("Dev worker should be initialized before sending messages."); | ||
| this.#worker.postMessage(message); | ||
| } | ||
| onMessage(listener) { | ||
| this.#messageListeners.add(listener); | ||
| } | ||
| offMessage(listener) { | ||
| this.#messageListeners.delete(listener); | ||
| } | ||
| async close(cause) { | ||
| if (this.closed) return; | ||
| this.closed = true; | ||
| this.#hooks.onClose?.(this, cause); | ||
| this.#hooks = {}; | ||
| const onError = (error) => consola$1.error(error); | ||
| await this.#closeWorker().catch(onError); | ||
| await this.#closeProxy().catch(onError); | ||
| await this.#closeSocket().catch(onError); | ||
| } | ||
| [Symbol.for("nodejs.util.inspect.custom")]() { | ||
| const status = this.closed ? "closed" : this.ready ? "ready" : "pending"; | ||
| return `NodeDevWorker#${this.#name}(${status})`; | ||
| } | ||
| #initWorker() { | ||
| if (!existsSync(this.#entry)) { | ||
| this.close(`worker entry not found in "${this.#entry}".`); | ||
| return; | ||
| } | ||
| const worker = new Worker(this.#entry, { | ||
| env: { ...process.env }, | ||
| workerData: { | ||
| name: this.#name, | ||
| ...this.#data | ||
| } | ||
| }); | ||
| worker.once("exit", (code) => { | ||
| worker._exitCode = code; | ||
| this.close(`worker exited with code ${code}`); | ||
| }); | ||
| worker.once("error", (error) => { | ||
| consola$1.error(`Worker error:`, error); | ||
| this.close(error); | ||
| }); | ||
| worker.on("message", (message) => { | ||
| if (message?.address) { | ||
| this.#address = message.address; | ||
| this.#hooks.onReady?.(this, this.#address); | ||
| } | ||
| for (const listener of this.#messageListeners) listener(message); | ||
| }); | ||
| this.#worker = worker; | ||
| } | ||
| async #closeProxy() { | ||
| this.#proxy?.proxy?.close(() => {}); | ||
| this.#proxy = void 0; | ||
| } | ||
| async #closeSocket() { | ||
| const socketPath = this.#address?.socketPath; | ||
| if (socketPath && socketPath[0] !== "\0" && !socketPath.startsWith(String.raw`\\.\pipe`)) await rm(socketPath).catch(() => {}); | ||
| this.#address = void 0; | ||
| } | ||
| async #closeWorker() { | ||
| if (!this.#worker) return; | ||
| this.#worker.postMessage({ event: "shutdown" }); | ||
| if (!this.#worker._exitCode && !a && !T) await new Promise((resolve$2) => { | ||
| const gracefulShutdownTimeoutMs = Number.parseInt(process.env.NITRO_SHUTDOWN_TIMEOUT || "", 10) || 5e3; | ||
| const timeout = setTimeout(() => { | ||
| if (process.env.DEBUG) consola$1.warn(`force closing dev worker...`); | ||
| }, gracefulShutdownTimeoutMs); | ||
| this.#worker?.on("message", (message) => { | ||
| if (message.event === "exit") { | ||
| clearTimeout(timeout); | ||
| resolve$2(); | ||
| } | ||
| }); | ||
| }); | ||
| this.#worker.removeAllListeners(); | ||
| await this.#worker.terminate().catch((error) => { | ||
| consola$1.error(error); | ||
| }); | ||
| this.#worker = void 0; | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region src/dev/vfs.ts | ||
| function createVFSHandler(nitro) { | ||
| return defineHandler(async (event) => { | ||
| const { socket } = event.runtime?.node?.req || {}; | ||
| const ip = getRequestIP(event, { xForwardedFor: !socket?.remoteAddress && !socket?.localAddress && Object.keys(socket?.address?.() || {}).length === 0 && socket?.readable && socket?.writable && !socket?.remotePort }); | ||
| if (!(ip && /^::1$|^127\.\d+\.\d+\.\d+$/.test(ip))) throw new HTTPError({ | ||
| statusText: `Forbidden IP: "${ip || "?"}"`, | ||
| status: 403 | ||
| }); | ||
| const vfsEntries = { | ||
| ...nitro.vfs, | ||
| ...nitro.options.virtual | ||
| }; | ||
| const url = event.context.params?._ || ""; | ||
| const isJson = url.endsWith(".json") || event.req.headers.get("accept")?.includes("application/json"); | ||
| const id = decodeURIComponent(url.replace(/^(\.json)?\/?/, "") || ""); | ||
| if (id && !(id in vfsEntries)) throw new HTTPError({ | ||
| message: "File not found", | ||
| status: 404 | ||
| }); | ||
| let content = id ? vfsEntries[id] : void 0; | ||
| if (typeof content === "function") content = await content(); | ||
| if (isJson) return { | ||
| rootDir: nitro.options.rootDir, | ||
| entries: Object.keys(vfsEntries).map((id$1) => ({ | ||
| id: id$1, | ||
| path: "/_vfs.json/" + encodeURIComponent(id$1) | ||
| })), | ||
| current: id ? { | ||
| id, | ||
| content | ||
| } : null | ||
| }; | ||
| const directories = { [nitro.options.rootDir]: {} }; | ||
| const fpaths = Object.keys(vfsEntries); | ||
| for (const item of fpaths) { | ||
| const segments = item.replace(nitro.options.rootDir, "").split("/").filter(Boolean); | ||
| let currentDir = item.startsWith(nitro.options.rootDir) ? directories[nitro.options.rootDir] : directories; | ||
| for (const segment of segments) { | ||
| if (!currentDir[segment]) currentDir[segment] = {}; | ||
| currentDir = currentDir[segment]; | ||
| } | ||
| } | ||
| const generateHTML = (directory, path$1 = []) => Object.entries(directory).map(([fname, value = {}]) => { | ||
| const subpath = [...path$1, fname]; | ||
| const key = subpath.join("/"); | ||
| const encodedUrl = encodeURIComponent(key); | ||
| const linkClass = url === `/${encodedUrl}` ? "bg-gray-700 text-white" : "hover:bg-gray-800 text-gray-200"; | ||
| return Object.keys(value).length === 0 ? ` | ||
| <li class="flex flex-nowrap"> | ||
| <a href="/_vfs/${encodedUrl}" class="w-full text-sm px-2 py-1 border-b border-gray-10 ${linkClass}"> | ||
| ${fname} | ||
| </a> | ||
| </li> | ||
| ` : ` | ||
| <li> | ||
| <details ${url.startsWith(`/${encodedUrl}`) ? "open" : ""}> | ||
| <summary class="w-full text-sm px-2 py-1 border-b border-gray-10 hover:bg-gray-800 text-gray-200"> | ||
| ${fname} | ||
| </summary> | ||
| <ul class="ml-4"> | ||
| ${generateHTML(value, subpath)} | ||
| </ul> | ||
| </details> | ||
| </li> | ||
| `; | ||
| }).join(""); | ||
| const rootDirectory = directories[nitro.options.rootDir]; | ||
| delete directories[nitro.options.rootDir]; | ||
| const files = ` | ||
| <div class="h-full overflow-auto border-r border-gray:10"> | ||
| <p class="text-white text-bold text-center py-1 opacity-50">Virtual Files</p> | ||
| <ul class="flex flex-col">${generateHTML(rootDirectory, [nitro.options.rootDir]) + generateHTML(directories)}</ul> | ||
| </div> | ||
| `; | ||
| const file = id ? editorTemplate({ | ||
| readOnly: true, | ||
| language: id.endsWith("html") ? "html" : "javascript", | ||
| theme: "vs-dark", | ||
| value: content, | ||
| wordWrap: "wordWrapColumn", | ||
| wordWrapColumn: 80 | ||
| }) : ` | ||
| <div class="w-full h-full flex opacity-50"> | ||
| <h1 class="text-white m-auto">Select a virtual file to inspect</h1> | ||
| </div> | ||
| `; | ||
| event.res.headers.set("Content-Type", "text/html; charset=utf-8"); | ||
| return ` | ||
| <!doctype html> | ||
| <html> | ||
| <head> | ||
| <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@unocss/reset/tailwind.min.css" /> | ||
| <link rel="stylesheet" data-name="vs/editor/editor.main" href="${vsUrl}/editor/editor.main.min.css"> | ||
| <script src="https://cdn.jsdelivr.net/npm/@unocss/runtime"><\/script> | ||
| <style> | ||
| html { | ||
| background: #1E1E1E; | ||
| color: white; | ||
| } | ||
| [un-cloak] { | ||
| display: none; | ||
| } | ||
| </style> | ||
| </head> | ||
| <body class="bg-[#1E1E1E]"> | ||
| <div un-cloak class="h-screen grid grid-cols-[300px_1fr]"> | ||
| ${files} | ||
| ${file} | ||
| </div> | ||
| </body> | ||
| </html>`; | ||
| }); | ||
| } | ||
| const monacoUrl = `https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.30.0/min`; | ||
| const vsUrl = `${monacoUrl}/vs`; | ||
| const editorTemplate = (options) => ` | ||
| <div id="editor" class="min-h-screen w-full h-full"></div> | ||
| <script src="${vsUrl}/loader.min.js"><\/script> | ||
| <script> | ||
| require.config({ paths: { vs: '${vsUrl}' } }) | ||
| const proxy = URL.createObjectURL(new Blob([\` | ||
| self.MonacoEnvironment = { baseUrl: '${monacoUrl}' } | ||
| importScripts('${vsUrl}/base/worker/workerMain.min.js') | ||
| \`], { type: 'text/javascript' })) | ||
| window.MonacoEnvironment = { getWorkerUrl: () => proxy } | ||
| setTimeout(() => { | ||
| require(['vs/editor/editor.main'], function () { | ||
| monaco.editor.create(document.getElementById('editor'), ${JSON.stringify(options)}) | ||
| }) | ||
| }, 0); | ||
| <\/script> | ||
| `; | ||
| //#endregion | ||
| //#region src/runtime/internal/error/utils.ts | ||
| function defineNitroErrorHandler(handler) { | ||
| return handler; | ||
| } | ||
| //#endregion | ||
| //#region src/runtime/internal/error/dev.ts | ||
| var dev_default = defineNitroErrorHandler(async function defaultNitroErrorHandler(error, event) { | ||
| const res = await defaultHandler(error, event); | ||
| return new FastResponse(typeof res.body === "string" ? res.body : JSON.stringify(res.body, null, 2), res); | ||
| }); | ||
| async function defaultHandler(error, event, opts) { | ||
| const isSensitive = error.unhandled; | ||
| const status = error.status || 500; | ||
| const url = getRequestURL(event, { | ||
| xForwardedHost: true, | ||
| xForwardedProto: true | ||
| }); | ||
| if (status === 404) { | ||
| const baseURL = import.meta.baseURL || "/"; | ||
| if (/^\/[^/]/.test(baseURL) && !url.pathname.startsWith(baseURL)) return { | ||
| status: 302, | ||
| statusText: "Found", | ||
| headers: { location: `${baseURL}${url.pathname.slice(1)}${url.search}` }, | ||
| body: `Redirecting...` | ||
| }; | ||
| } | ||
| await loadStackTrace(error).catch(consola$1.error); | ||
| const youch = new Youch(); | ||
| if (isSensitive && !opts?.silent) { | ||
| const tags = [error.unhandled && "[unhandled]"].filter(Boolean).join(" "); | ||
| const ansiError = await (await youch.toANSI(error)).replaceAll(process.cwd(), "."); | ||
| consola$1.error(`[request error] ${tags} [${event.req.method}] ${url}\n\n`, ansiError); | ||
| } | ||
| const useJSON = opts?.json || !event.req.headers.get("accept")?.includes("text/html"); | ||
| const headers = { | ||
| "content-type": useJSON ? "application/json" : "text/html", | ||
| "x-content-type-options": "nosniff", | ||
| "x-frame-options": "DENY", | ||
| "referrer-policy": "no-referrer", | ||
| "content-security-policy": "script-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self';" | ||
| }; | ||
| if (status === 404 || !event.res.headers.has("cache-control")) headers["cache-control"] = "no-cache"; | ||
| const body = useJSON ? { | ||
| error: true, | ||
| url, | ||
| status, | ||
| statusText: error.statusText, | ||
| message: error.message, | ||
| data: error.data, | ||
| stack: error.stack?.split("\n").map((line) => line.trim()) | ||
| } : await youch.toHTML(error, { request: { | ||
| url: url.href, | ||
| method: event.req.method, | ||
| headers: Object.fromEntries(event.req.headers.entries()) | ||
| } }); | ||
| return { | ||
| status, | ||
| statusText: error.statusText, | ||
| headers, | ||
| body | ||
| }; | ||
| } | ||
| async function loadStackTrace(error) { | ||
| if (!(error instanceof Error)) return; | ||
| const parsed = await new ErrorParser().defineSourceLoader(sourceLoader).parse(error); | ||
| const stack = error.message + "\n" + parsed.frames.map((frame) => fmtFrame(frame)).join("\n"); | ||
| Object.defineProperty(error, "stack", { value: stack }); | ||
| if (error.cause) await loadStackTrace(error.cause).catch(consola$1.error); | ||
| } | ||
| async function sourceLoader(frame) { | ||
| if (!frame.fileName || frame.fileType !== "fs" || frame.type === "native") return; | ||
| if (frame.type === "app") { | ||
| const rawSourceMap = await readFile(`${frame.fileName}.map`, "utf8").catch(() => {}); | ||
| if (rawSourceMap) { | ||
| const originalPosition = (await new SourceMapConsumer(rawSourceMap)).originalPositionFor({ | ||
| line: frame.lineNumber, | ||
| column: frame.columnNumber | ||
| }); | ||
| if (originalPosition.source && originalPosition.line) { | ||
| frame.fileName = resolve(dirname(frame.fileName), originalPosition.source); | ||
| frame.lineNumber = originalPosition.line; | ||
| frame.columnNumber = originalPosition.column || 0; | ||
| } | ||
| } | ||
| } | ||
| const contents = await readFile(frame.fileName, "utf8").catch(() => {}); | ||
| return contents ? { contents } : void 0; | ||
| } | ||
| function fmtFrame(frame) { | ||
| if (frame.type === "native") return frame.raw; | ||
| const src = `${frame.fileName || ""}:${frame.lineNumber}:${frame.columnNumber})`; | ||
| return frame.functionName ? `at ${frame.functionName} (${src}` : `at ${src}`; | ||
| } | ||
| //#endregion | ||
| //#region src/dev/app.ts | ||
| var NitroDevApp = class { | ||
| nitro; | ||
| fetch; | ||
| constructor(nitro, catchAllHandler) { | ||
| this.nitro = nitro; | ||
| const app = this.#createApp(catchAllHandler); | ||
| this.fetch = app.fetch.bind(app); | ||
| } | ||
| #createApp(catchAllHandler) { | ||
| const app = new H3({ | ||
| debug: true, | ||
| onError: async (error, event) => { | ||
| const errorHandler = this.nitro.options.devErrorHandler || dev_default; | ||
| await loadStackTrace(error).catch(() => {}); | ||
| return errorHandler(error, event, { defaultHandler }); | ||
| } | ||
| }); | ||
| for (const h of this.nitro.options.devHandlers) { | ||
| const handler = toEventHandler(h.handler); | ||
| if (!handler) { | ||
| this.nitro.logger.warn("Invalid dev handler:", h); | ||
| continue; | ||
| } | ||
| if (h.middleware || !h.route) if (h.route) app.use(h.route, handler, { method: h.method }); | ||
| else app.use(handler, { method: h.method }); | ||
| else app.on(h.method || "", h.route, handler, { meta: h.meta }); | ||
| } | ||
| app.get("/_vfs/**", createVFSHandler(this.nitro)); | ||
| for (const asset of this.nitro.options.publicAssets) { | ||
| const assetBase = joinURL(this.nitro.options.baseURL, asset.baseURL || "/"); | ||
| app.use(joinURL(assetBase, "**"), (event) => serveStaticDir(event, { | ||
| dir: asset.dir, | ||
| base: assetBase, | ||
| fallthrough: asset.fallthrough | ||
| })); | ||
| } | ||
| const routes = Object.keys(this.nitro.options.devProxy).sort().reverse(); | ||
| for (const route of routes) { | ||
| let opts = this.nitro.options.devProxy[route]; | ||
| if (typeof opts === "string") opts = { target: opts }; | ||
| const proxy = createHTTPProxy(opts); | ||
| app.all(route, proxy.handleEvent); | ||
| } | ||
| if (catchAllHandler) app.all("/**", catchAllHandler); | ||
| return app; | ||
| } | ||
| }; | ||
| function serveStaticDir(event, opts) { | ||
| const dir = resolve$1(opts.dir) + "/"; | ||
| const r = (id) => { | ||
| if (!id.startsWith(opts.base) || !extname$1(id)) return; | ||
| const resolved = join$1(dir, id.slice(opts.base.length)); | ||
| if (resolved.startsWith(dir)) return resolved; | ||
| }; | ||
| return serveStatic(event, { | ||
| fallthrough: opts.fallthrough, | ||
| getMeta: async (id) => { | ||
| const path$1 = r(id); | ||
| if (!path$1) return; | ||
| const s = await stat(path$1).catch(() => null); | ||
| if (!s?.isFile()) return; | ||
| const ext = extname$1(path$1); | ||
| return { | ||
| size: s.size, | ||
| mtime: s.mtime, | ||
| type: src_default.getType(ext) || "application/octet-stream" | ||
| }; | ||
| }, | ||
| getContents(id) { | ||
| const path$1 = r(id); | ||
| if (!path$1) return; | ||
| const stream = createReadStream(path$1); | ||
| const acceptEncoding = event.req.headers.get("accept-encoding") || ""; | ||
| if (acceptEncoding.includes("br")) { | ||
| event.res.headers.set("Content-Encoding", "br"); | ||
| event.res.headers.delete("Content-Length"); | ||
| event.res.headers.set("Vary", "Accept-Encoding"); | ||
| return stream.pipe(createBrotliCompress()); | ||
| } else if (acceptEncoding.includes("gzip")) { | ||
| event.res.headers.set("Content-Encoding", "gzip"); | ||
| event.res.headers.delete("Content-Length"); | ||
| event.res.headers.set("Vary", "Accept-Encoding"); | ||
| return stream.pipe(createGzip()); | ||
| } | ||
| return stream; | ||
| } | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region src/dev/server.ts | ||
| function createDevServer(nitro) { | ||
| return new NitroDevServer(nitro); | ||
| } | ||
| var NitroDevServer = class NitroDevServer extends NitroDevApp { | ||
| #entry; | ||
| #workerData = {}; | ||
| #listeners = []; | ||
| #watcher; | ||
| #workers = []; | ||
| #workerIdCtr = 0; | ||
| #workerError; | ||
| #building = true; | ||
| #buildError; | ||
| #messageListeners = /* @__PURE__ */ new Set(); | ||
| constructor(nitro) { | ||
| super(nitro, async (event) => { | ||
| const worker = await this.#getWorker(); | ||
| if (!worker) return this.#generateError(); | ||
| return worker.fetch(event.req); | ||
| }); | ||
| for (const key of Object.getOwnPropertyNames(NitroDevServer.prototype)) { | ||
| const value = this[key]; | ||
| if (typeof value === "function" && key !== "constructor") this[key] = value.bind(this); | ||
| } | ||
| nitro.fetch = this.fetch.bind(this); | ||
| this.#entry = resolve$1(nitro.options.output.dir, nitro.options.output.serverDir, "index.mjs"); | ||
| nitro.hooks.hook("close", () => this.close()); | ||
| nitro.hooks.hook("dev:start", () => { | ||
| this.#building = true; | ||
| this.#buildError = void 0; | ||
| }); | ||
| nitro.hooks.hook("dev:reload", (payload) => { | ||
| this.#buildError = void 0; | ||
| this.#building = false; | ||
| if (payload?.entry) this.#entry = payload.entry; | ||
| if (payload?.workerData) this.#workerData = payload.workerData; | ||
| this.reload(); | ||
| }); | ||
| nitro.hooks.hook("dev:error", (cause) => { | ||
| this.#buildError = cause; | ||
| this.#building = false; | ||
| for (const worker of this.#workers) worker.close(); | ||
| }); | ||
| if (nitro.options.devServer.watch.length > 0) { | ||
| const debouncedReload = debounce(() => this.reload()); | ||
| this.#watcher = watch$1(nitro.options.devServer.watch, nitro.options.watchOptions); | ||
| this.#watcher.on("add", debouncedReload).on("change", debouncedReload); | ||
| } | ||
| } | ||
| async upgrade(req, socket, head) { | ||
| const worker = await this.#getWorker(); | ||
| if (!worker) throw new HTTPError({ | ||
| status: 503, | ||
| statusText: "No worker available." | ||
| }); | ||
| return worker.upgrade(req, socket, head); | ||
| } | ||
| listen(opts) { | ||
| const server = serve({ | ||
| ...opts, | ||
| fetch: this.fetch, | ||
| gracefulShutdown: false | ||
| }); | ||
| this.#listeners.push(server); | ||
| if (server.node?.server) server.node.server.on("upgrade", (req, sock, head) => this.upgrade(req, sock, head)); | ||
| return server; | ||
| } | ||
| async close() { | ||
| await Promise.all([ | ||
| Promise.all(this.#listeners.map((l) => l.close())).then(() => { | ||
| this.#listeners = []; | ||
| }), | ||
| Promise.all(this.#workers.map((w) => w.close())).then(() => { | ||
| this.#workers = []; | ||
| }), | ||
| Promise.resolve(this.#watcher?.close()).then(() => { | ||
| this.#watcher = void 0; | ||
| }) | ||
| ].map((p) => p.catch((error) => { | ||
| consola$1.error(error); | ||
| }))); | ||
| } | ||
| reload() { | ||
| for (const worker$1 of this.#workers) worker$1.close(); | ||
| const worker = new NodeDevWorker({ | ||
| name: `Nitro_${this.#workerIdCtr++}`, | ||
| entry: this.#entry, | ||
| data: { | ||
| ...this.#workerData, | ||
| globals: { | ||
| __NITRO_RUNTIME_CONFIG__: this.nitro.options.runtimeConfig, | ||
| ...this.#workerData.globals | ||
| } | ||
| }, | ||
| hooks: { | ||
| onClose: (worker$1, cause) => { | ||
| this.#workerError = cause; | ||
| const index = this.#workers.indexOf(worker$1); | ||
| if (index !== -1) this.#workers.splice(index, 1); | ||
| }, | ||
| onReady: async (_worker, addr) => { | ||
| writeDevBuildInfo(this.nitro, addr).catch(() => {}); | ||
| } | ||
| } | ||
| }); | ||
| if (!worker.closed) { | ||
| for (const listener of this.#messageListeners) worker.onMessage(listener); | ||
| this.#workers.unshift(worker); | ||
| } | ||
| } | ||
| sendMessage(message) { | ||
| for (const worker of this.#workers) if (!worker.closed) worker.sendMessage(message); | ||
| } | ||
| onMessage(listener) { | ||
| this.#messageListeners.add(listener); | ||
| for (const worker of this.#workers) worker.onMessage(listener); | ||
| } | ||
| offMessage(listener) { | ||
| this.#messageListeners.delete(listener); | ||
| for (const worker of this.#workers) worker.offMessage(listener); | ||
| } | ||
| async #getWorker() { | ||
| let retry = 0; | ||
| const maxRetries = a || T ? 100 : 10; | ||
| while (this.#building || ++retry < maxRetries) { | ||
| if ((this.#workers.length === 0 || this.#buildError) && !this.#building) return; | ||
| const activeWorker = this.#workers.find((w) => w.ready); | ||
| if (activeWorker) return activeWorker; | ||
| await new Promise((resolve$2) => setTimeout(resolve$2, 600)); | ||
| } | ||
| } | ||
| #generateError() { | ||
| const error = this.#buildError || this.#workerError; | ||
| if (error) { | ||
| try { | ||
| error.unhandled = false; | ||
| let id = error.id || error.path; | ||
| if (id) { | ||
| const cause = error.errors?.[0]; | ||
| const loc = error.location || error.loc || cause?.location || cause?.loc; | ||
| if (loc) id += `:${loc.line}:${loc.column}`; | ||
| error.stack = (error.stack || "").replace(/(^\s*at\s+.+)/m, ` at ${id}\n$1`); | ||
| } | ||
| } catch {} | ||
| return new HTTPError(error); | ||
| } | ||
| return new Response(JSON.stringify({ | ||
| error: "Dev server is unavailable.", | ||
| hint: "Please reload the page and check the console for errors if the issue persists." | ||
| }, null, 2), { | ||
| status: 503, | ||
| statusText: "Dev server is unavailable", | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| "Cache-Control": "no-store", | ||
| Refresh: "3" | ||
| } | ||
| }); | ||
| } | ||
| }; | ||
| //#endregion | ||
| export { NodeDevWorker as i, createDevServer as n, NitroDevApp as r, NitroDevServer as t }; |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| import { join, relative, resolve, sep } from "node:path"; | ||
| import { lstat, readdir, realpath, stat } from "node:fs/promises"; | ||
| import { stat as stat$1, unwatchFile, watch, watchFile } from "fs"; | ||
| import * as sysPath from "path"; | ||
| import { type } from "os"; | ||
| import { lstat as lstat$1, open, readdir as readdir$1, realpath as realpath$1, stat as stat$2 } from "fs/promises"; | ||
| import { EventEmitter } from "events"; | ||
| import { Readable } from "node:stream"; | ||
| //#region node_modules/.pnpm/readdirp@4.1.2/node_modules/readdirp/esm/index.js | ||
| const EntryTypes = { | ||
| FILE_TYPE: "files", | ||
| DIR_TYPE: "directories", | ||
| FILE_DIR_TYPE: "files_directories", | ||
| EVERYTHING_TYPE: "all" | ||
| }; | ||
| const defaultOptions = { | ||
| root: ".", | ||
| fileFilter: (_entryInfo) => true, | ||
| directoryFilter: (_entryInfo) => true, | ||
| type: EntryTypes.FILE_TYPE, | ||
| lstat: false, | ||
| depth: 2147483648, | ||
| alwaysStat: false, | ||
| highWaterMark: 4096 | ||
| }; | ||
| Object.freeze(defaultOptions); | ||
| const RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR"; | ||
| const NORMAL_FLOW_ERRORS = new Set([ | ||
| "ENOENT", | ||
| "EPERM", | ||
| "EACCES", | ||
| "ELOOP", | ||
| RECURSIVE_ERROR_CODE | ||
| ]); | ||
| const ALL_TYPES = [ | ||
| EntryTypes.DIR_TYPE, | ||
| EntryTypes.EVERYTHING_TYPE, | ||
| EntryTypes.FILE_DIR_TYPE, | ||
| EntryTypes.FILE_TYPE | ||
| ]; | ||
| const DIR_TYPES = new Set([ | ||
| EntryTypes.DIR_TYPE, | ||
| EntryTypes.EVERYTHING_TYPE, | ||
| EntryTypes.FILE_DIR_TYPE | ||
| ]); | ||
| const FILE_TYPES = new Set([ | ||
| EntryTypes.EVERYTHING_TYPE, | ||
| EntryTypes.FILE_DIR_TYPE, | ||
| EntryTypes.FILE_TYPE | ||
| ]); | ||
| const isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code); | ||
| const wantBigintFsStats = process.platform === "win32"; | ||
| const emptyFn = (_entryInfo) => true; | ||
| const normalizeFilter = (filter) => { | ||
| if (filter === void 0) return emptyFn; | ||
| if (typeof filter === "function") return filter; | ||
| if (typeof filter === "string") { | ||
| const fl = filter.trim(); | ||
| return (entry) => entry.basename === fl; | ||
| } | ||
| if (Array.isArray(filter)) { | ||
| const trItems = filter.map((item) => item.trim()); | ||
| return (entry) => trItems.some((f) => entry.basename === f); | ||
| } | ||
| return emptyFn; | ||
| }; | ||
| /** Readable readdir stream, emitting new files as they're being listed. */ | ||
| var ReaddirpStream = class extends Readable { | ||
| constructor(options = {}) { | ||
| super({ | ||
| objectMode: true, | ||
| autoDestroy: true, | ||
| highWaterMark: options.highWaterMark | ||
| }); | ||
| const opts = { | ||
| ...defaultOptions, | ||
| ...options | ||
| }; | ||
| const { root, type: type$1 } = opts; | ||
| this._fileFilter = normalizeFilter(opts.fileFilter); | ||
| this._directoryFilter = normalizeFilter(opts.directoryFilter); | ||
| const statMethod = opts.lstat ? lstat : stat; | ||
| if (wantBigintFsStats) this._stat = (path$2) => statMethod(path$2, { bigint: true }); | ||
| else this._stat = statMethod; | ||
| this._maxDepth = opts.depth ?? defaultOptions.depth; | ||
| this._wantsDir = type$1 ? DIR_TYPES.has(type$1) : false; | ||
| this._wantsFile = type$1 ? FILE_TYPES.has(type$1) : false; | ||
| this._wantsEverything = type$1 === EntryTypes.EVERYTHING_TYPE; | ||
| this._root = resolve(root); | ||
| this._isDirent = !opts.alwaysStat; | ||
| this._statsProp = this._isDirent ? "dirent" : "stats"; | ||
| this._rdOptions = { | ||
| encoding: "utf8", | ||
| withFileTypes: this._isDirent | ||
| }; | ||
| this.parents = [this._exploreDir(root, 1)]; | ||
| this.reading = false; | ||
| this.parent = void 0; | ||
| } | ||
| async _read(batch) { | ||
| if (this.reading) return; | ||
| this.reading = true; | ||
| try { | ||
| while (!this.destroyed && batch > 0) { | ||
| const par = this.parent; | ||
| const fil = par && par.files; | ||
| if (fil && fil.length > 0) { | ||
| const { path: path$2, depth } = par; | ||
| const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path$2)); | ||
| const awaited = await Promise.all(slice); | ||
| for (const entry of awaited) { | ||
| if (!entry) continue; | ||
| if (this.destroyed) return; | ||
| const entryType = await this._getEntryType(entry); | ||
| if (entryType === "directory" && this._directoryFilter(entry)) { | ||
| if (depth <= this._maxDepth) this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); | ||
| if (this._wantsDir) { | ||
| this.push(entry); | ||
| batch--; | ||
| } | ||
| } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) { | ||
| if (this._wantsFile) { | ||
| this.push(entry); | ||
| batch--; | ||
| } | ||
| } | ||
| } | ||
| } else { | ||
| const parent = this.parents.pop(); | ||
| if (!parent) { | ||
| this.push(null); | ||
| break; | ||
| } | ||
| this.parent = await parent; | ||
| if (this.destroyed) return; | ||
| } | ||
| } | ||
| } catch (error) { | ||
| this.destroy(error); | ||
| } finally { | ||
| this.reading = false; | ||
| } | ||
| } | ||
| async _exploreDir(path$2, depth) { | ||
| let files; | ||
| try { | ||
| files = await readdir(path$2, this._rdOptions); | ||
| } catch (error) { | ||
| this._onError(error); | ||
| } | ||
| return { | ||
| files, | ||
| depth, | ||
| path: path$2 | ||
| }; | ||
| } | ||
| async _formatEntry(dirent, path$2) { | ||
| let entry; | ||
| const basename$2 = this._isDirent ? dirent.name : dirent; | ||
| try { | ||
| const fullPath = resolve(join(path$2, basename$2)); | ||
| entry = { | ||
| path: relative(this._root, fullPath), | ||
| fullPath, | ||
| basename: basename$2 | ||
| }; | ||
| entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); | ||
| } catch (err) { | ||
| this._onError(err); | ||
| return; | ||
| } | ||
| return entry; | ||
| } | ||
| _onError(err) { | ||
| if (isNormalFlowError(err) && !this.destroyed) this.emit("warn", err); | ||
| else this.destroy(err); | ||
| } | ||
| async _getEntryType(entry) { | ||
| if (!entry && this._statsProp in entry) return ""; | ||
| const stats = entry[this._statsProp]; | ||
| if (stats.isFile()) return "file"; | ||
| if (stats.isDirectory()) return "directory"; | ||
| if (stats && stats.isSymbolicLink()) { | ||
| const full = entry.fullPath; | ||
| try { | ||
| const entryRealPath = await realpath(full); | ||
| const entryRealPathStats = await lstat(entryRealPath); | ||
| if (entryRealPathStats.isFile()) return "file"; | ||
| if (entryRealPathStats.isDirectory()) { | ||
| const len = entryRealPath.length; | ||
| if (full.startsWith(entryRealPath) && full.substr(len, 1) === sep) { | ||
| const recursiveError = /* @__PURE__ */ new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`); | ||
| recursiveError.code = RECURSIVE_ERROR_CODE; | ||
| return this._onError(recursiveError); | ||
| } | ||
| return "directory"; | ||
| } | ||
| } catch (error) { | ||
| this._onError(error); | ||
| return ""; | ||
| } | ||
| } | ||
| } | ||
| _includeAsFile(entry) { | ||
| const stats = entry && entry[this._statsProp]; | ||
| return stats && this._wantsEverything && !stats.isDirectory(); | ||
| } | ||
| }; | ||
| /** | ||
| * Streaming version: Reads all files and directories in given root recursively. | ||
| * Consumes ~constant small amount of RAM. | ||
| * @param root Root directory | ||
| * @param options Options to specify root (start directory), filters and recursion depth | ||
| */ | ||
| function readdirp(root, options = {}) { | ||
| let type$1 = options.entryType || options.type; | ||
| if (type$1 === "both") type$1 = EntryTypes.FILE_DIR_TYPE; | ||
| if (type$1) options.type = type$1; | ||
| if (!root) throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)"); | ||
| else if (typeof root !== "string") throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)"); | ||
| else if (type$1 && !ALL_TYPES.includes(type$1)) throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`); | ||
| options.root = root; | ||
| return new ReaddirpStream(options); | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/chokidar@4.0.3/node_modules/chokidar/esm/handler.js | ||
| const STR_DATA = "data"; | ||
| const STR_END = "end"; | ||
| const STR_CLOSE = "close"; | ||
| const EMPTY_FN = () => {}; | ||
| const pl = process.platform; | ||
| const isWindows = pl === "win32"; | ||
| const isMacos = pl === "darwin"; | ||
| const isLinux = pl === "linux"; | ||
| const isFreeBSD = pl === "freebsd"; | ||
| const isIBMi = type() === "OS400"; | ||
| const EVENTS = { | ||
| ALL: "all", | ||
| READY: "ready", | ||
| ADD: "add", | ||
| CHANGE: "change", | ||
| ADD_DIR: "addDir", | ||
| UNLINK: "unlink", | ||
| UNLINK_DIR: "unlinkDir", | ||
| RAW: "raw", | ||
| ERROR: "error" | ||
| }; | ||
| const EV = EVENTS; | ||
| const THROTTLE_MODE_WATCH = "watch"; | ||
| const statMethods = { | ||
| lstat: lstat$1, | ||
| stat: stat$2 | ||
| }; | ||
| const KEY_LISTENERS = "listeners"; | ||
| const KEY_ERR = "errHandlers"; | ||
| const KEY_RAW = "rawEmitters"; | ||
| const HANDLER_KEYS = [ | ||
| KEY_LISTENERS, | ||
| KEY_ERR, | ||
| KEY_RAW | ||
| ]; | ||
| const binaryExtensions = new Set([ | ||
| "3dm", | ||
| "3ds", | ||
| "3g2", | ||
| "3gp", | ||
| "7z", | ||
| "a", | ||
| "aac", | ||
| "adp", | ||
| "afdesign", | ||
| "afphoto", | ||
| "afpub", | ||
| "ai", | ||
| "aif", | ||
| "aiff", | ||
| "alz", | ||
| "ape", | ||
| "apk", | ||
| "appimage", | ||
| "ar", | ||
| "arj", | ||
| "asf", | ||
| "au", | ||
| "avi", | ||
| "bak", | ||
| "baml", | ||
| "bh", | ||
| "bin", | ||
| "bk", | ||
| "bmp", | ||
| "btif", | ||
| "bz2", | ||
| "bzip2", | ||
| "cab", | ||
| "caf", | ||
| "cgm", | ||
| "class", | ||
| "cmx", | ||
| "cpio", | ||
| "cr2", | ||
| "cur", | ||
| "dat", | ||
| "dcm", | ||
| "deb", | ||
| "dex", | ||
| "djvu", | ||
| "dll", | ||
| "dmg", | ||
| "dng", | ||
| "doc", | ||
| "docm", | ||
| "docx", | ||
| "dot", | ||
| "dotm", | ||
| "dra", | ||
| "DS_Store", | ||
| "dsk", | ||
| "dts", | ||
| "dtshd", | ||
| "dvb", | ||
| "dwg", | ||
| "dxf", | ||
| "ecelp4800", | ||
| "ecelp7470", | ||
| "ecelp9600", | ||
| "egg", | ||
| "eol", | ||
| "eot", | ||
| "epub", | ||
| "exe", | ||
| "f4v", | ||
| "fbs", | ||
| "fh", | ||
| "fla", | ||
| "flac", | ||
| "flatpak", | ||
| "fli", | ||
| "flv", | ||
| "fpx", | ||
| "fst", | ||
| "fvt", | ||
| "g3", | ||
| "gh", | ||
| "gif", | ||
| "graffle", | ||
| "gz", | ||
| "gzip", | ||
| "h261", | ||
| "h263", | ||
| "h264", | ||
| "icns", | ||
| "ico", | ||
| "ief", | ||
| "img", | ||
| "ipa", | ||
| "iso", | ||
| "jar", | ||
| "jpeg", | ||
| "jpg", | ||
| "jpgv", | ||
| "jpm", | ||
| "jxr", | ||
| "key", | ||
| "ktx", | ||
| "lha", | ||
| "lib", | ||
| "lvp", | ||
| "lz", | ||
| "lzh", | ||
| "lzma", | ||
| "lzo", | ||
| "m3u", | ||
| "m4a", | ||
| "m4v", | ||
| "mar", | ||
| "mdi", | ||
| "mht", | ||
| "mid", | ||
| "midi", | ||
| "mj2", | ||
| "mka", | ||
| "mkv", | ||
| "mmr", | ||
| "mng", | ||
| "mobi", | ||
| "mov", | ||
| "movie", | ||
| "mp3", | ||
| "mp4", | ||
| "mp4a", | ||
| "mpeg", | ||
| "mpg", | ||
| "mpga", | ||
| "mxu", | ||
| "nef", | ||
| "npx", | ||
| "numbers", | ||
| "nupkg", | ||
| "o", | ||
| "odp", | ||
| "ods", | ||
| "odt", | ||
| "oga", | ||
| "ogg", | ||
| "ogv", | ||
| "otf", | ||
| "ott", | ||
| "pages", | ||
| "pbm", | ||
| "pcx", | ||
| "pdb", | ||
| "pdf", | ||
| "pea", | ||
| "pgm", | ||
| "pic", | ||
| "png", | ||
| "pnm", | ||
| "pot", | ||
| "potm", | ||
| "potx", | ||
| "ppa", | ||
| "ppam", | ||
| "ppm", | ||
| "pps", | ||
| "ppsm", | ||
| "ppsx", | ||
| "ppt", | ||
| "pptm", | ||
| "pptx", | ||
| "psd", | ||
| "pya", | ||
| "pyc", | ||
| "pyo", | ||
| "pyv", | ||
| "qt", | ||
| "rar", | ||
| "ras", | ||
| "raw", | ||
| "resources", | ||
| "rgb", | ||
| "rip", | ||
| "rlc", | ||
| "rmf", | ||
| "rmvb", | ||
| "rpm", | ||
| "rtf", | ||
| "rz", | ||
| "s3m", | ||
| "s7z", | ||
| "scpt", | ||
| "sgi", | ||
| "shar", | ||
| "snap", | ||
| "sil", | ||
| "sketch", | ||
| "slk", | ||
| "smv", | ||
| "snk", | ||
| "so", | ||
| "stl", | ||
| "suo", | ||
| "sub", | ||
| "swf", | ||
| "tar", | ||
| "tbz", | ||
| "tbz2", | ||
| "tga", | ||
| "tgz", | ||
| "thmx", | ||
| "tif", | ||
| "tiff", | ||
| "tlz", | ||
| "ttc", | ||
| "ttf", | ||
| "txz", | ||
| "udf", | ||
| "uvh", | ||
| "uvi", | ||
| "uvm", | ||
| "uvp", | ||
| "uvs", | ||
| "uvu", | ||
| "viv", | ||
| "vob", | ||
| "war", | ||
| "wav", | ||
| "wax", | ||
| "wbmp", | ||
| "wdp", | ||
| "weba", | ||
| "webm", | ||
| "webp", | ||
| "whl", | ||
| "wim", | ||
| "wm", | ||
| "wma", | ||
| "wmv", | ||
| "wmx", | ||
| "woff", | ||
| "woff2", | ||
| "wrm", | ||
| "wvx", | ||
| "xbm", | ||
| "xif", | ||
| "xla", | ||
| "xlam", | ||
| "xls", | ||
| "xlsb", | ||
| "xlsm", | ||
| "xlsx", | ||
| "xlt", | ||
| "xltm", | ||
| "xltx", | ||
| "xm", | ||
| "xmind", | ||
| "xpi", | ||
| "xpm", | ||
| "xwd", | ||
| "xz", | ||
| "z", | ||
| "zip", | ||
| "zipx" | ||
| ]); | ||
| const isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase()); | ||
| const foreach = (val, fn) => { | ||
| if (val instanceof Set) val.forEach(fn); | ||
| else fn(val); | ||
| }; | ||
| const addAndConvert = (main, prop, item) => { | ||
| let container = main[prop]; | ||
| if (!(container instanceof Set)) main[prop] = container = new Set([container]); | ||
| container.add(item); | ||
| }; | ||
| const clearItem = (cont) => (key) => { | ||
| const set = cont[key]; | ||
| if (set instanceof Set) set.clear(); | ||
| else delete cont[key]; | ||
| }; | ||
| const delFromSet = (main, prop, item) => { | ||
| const container = main[prop]; | ||
| if (container instanceof Set) container.delete(item); | ||
| else if (container === item) delete main[prop]; | ||
| }; | ||
| const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; | ||
| const FsWatchInstances = /* @__PURE__ */ new Map(); | ||
| /** | ||
| * Instantiates the fs_watch interface | ||
| * @param path to be watched | ||
| * @param options to be passed to fs_watch | ||
| * @param listener main event handler | ||
| * @param errHandler emits info about errors | ||
| * @param emitRaw emits raw event data | ||
| * @returns {NativeFsWatcher} | ||
| */ | ||
| function createFsWatchInstance(path$2, options, listener, errHandler, emitRaw) { | ||
| const handleEvent = (rawEvent, evPath) => { | ||
| listener(path$2); | ||
| emitRaw(rawEvent, evPath, { watchedPath: path$2 }); | ||
| if (evPath && path$2 !== evPath) fsWatchBroadcast(sysPath.resolve(path$2, evPath), KEY_LISTENERS, sysPath.join(path$2, evPath)); | ||
| }; | ||
| try { | ||
| return watch(path$2, { persistent: options.persistent }, handleEvent); | ||
| } catch (error) { | ||
| errHandler(error); | ||
| return; | ||
| } | ||
| } | ||
| /** | ||
| * Helper for passing fs_watch event data to a collection of listeners | ||
| * @param fullPath absolute path bound to fs_watch instance | ||
| */ | ||
| const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => { | ||
| const cont = FsWatchInstances.get(fullPath); | ||
| if (!cont) return; | ||
| foreach(cont[listenerType], (listener) => { | ||
| listener(val1, val2, val3); | ||
| }); | ||
| }; | ||
| /** | ||
| * Instantiates the fs_watch interface or binds listeners | ||
| * to an existing one covering the same file system entry | ||
| * @param path | ||
| * @param fullPath absolute path | ||
| * @param options to be passed to fs_watch | ||
| * @param handlers container for event listener functions | ||
| */ | ||
| const setFsWatchListener = (path$2, fullPath, options, handlers) => { | ||
| const { listener, errHandler, rawEmitter } = handlers; | ||
| let cont = FsWatchInstances.get(fullPath); | ||
| let watcher; | ||
| if (!options.persistent) { | ||
| watcher = createFsWatchInstance(path$2, options, listener, errHandler, rawEmitter); | ||
| if (!watcher) return; | ||
| return watcher.close.bind(watcher); | ||
| } | ||
| if (cont) { | ||
| addAndConvert(cont, KEY_LISTENERS, listener); | ||
| addAndConvert(cont, KEY_ERR, errHandler); | ||
| addAndConvert(cont, KEY_RAW, rawEmitter); | ||
| } else { | ||
| watcher = createFsWatchInstance(path$2, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW)); | ||
| if (!watcher) return; | ||
| watcher.on(EV.ERROR, async (error) => { | ||
| const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); | ||
| if (cont) cont.watcherUnusable = true; | ||
| if (isWindows && error.code === "EPERM") try { | ||
| await (await open(path$2, "r")).close(); | ||
| broadcastErr(error); | ||
| } catch (err) {} | ||
| else broadcastErr(error); | ||
| }); | ||
| cont = { | ||
| listeners: listener, | ||
| errHandlers: errHandler, | ||
| rawEmitters: rawEmitter, | ||
| watcher | ||
| }; | ||
| FsWatchInstances.set(fullPath, cont); | ||
| } | ||
| return () => { | ||
| delFromSet(cont, KEY_LISTENERS, listener); | ||
| delFromSet(cont, KEY_ERR, errHandler); | ||
| delFromSet(cont, KEY_RAW, rawEmitter); | ||
| if (isEmptySet(cont.listeners)) { | ||
| cont.watcher.close(); | ||
| FsWatchInstances.delete(fullPath); | ||
| HANDLER_KEYS.forEach(clearItem(cont)); | ||
| cont.watcher = void 0; | ||
| Object.freeze(cont); | ||
| } | ||
| }; | ||
| }; | ||
| const FsWatchFileInstances = /* @__PURE__ */ new Map(); | ||
| /** | ||
| * Instantiates the fs_watchFile interface or binds listeners | ||
| * to an existing one covering the same file system entry | ||
| * @param path to be watched | ||
| * @param fullPath absolute path | ||
| * @param options options to be passed to fs_watchFile | ||
| * @param handlers container for event listener functions | ||
| * @returns closer | ||
| */ | ||
| const setFsWatchFileListener = (path$2, fullPath, options, handlers) => { | ||
| const { listener, rawEmitter } = handlers; | ||
| let cont = FsWatchFileInstances.get(fullPath); | ||
| const copts = cont && cont.options; | ||
| if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { | ||
| unwatchFile(fullPath); | ||
| cont = void 0; | ||
| } | ||
| if (cont) { | ||
| addAndConvert(cont, KEY_LISTENERS, listener); | ||
| addAndConvert(cont, KEY_RAW, rawEmitter); | ||
| } else { | ||
| cont = { | ||
| listeners: listener, | ||
| rawEmitters: rawEmitter, | ||
| options, | ||
| watcher: watchFile(fullPath, options, (curr, prev) => { | ||
| foreach(cont.rawEmitters, (rawEmitter$1) => { | ||
| rawEmitter$1(EV.CHANGE, fullPath, { | ||
| curr, | ||
| prev | ||
| }); | ||
| }); | ||
| const currmtime = curr.mtimeMs; | ||
| if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) foreach(cont.listeners, (listener$1) => listener$1(path$2, curr)); | ||
| }) | ||
| }; | ||
| FsWatchFileInstances.set(fullPath, cont); | ||
| } | ||
| return () => { | ||
| delFromSet(cont, KEY_LISTENERS, listener); | ||
| delFromSet(cont, KEY_RAW, rawEmitter); | ||
| if (isEmptySet(cont.listeners)) { | ||
| FsWatchFileInstances.delete(fullPath); | ||
| unwatchFile(fullPath); | ||
| cont.options = cont.watcher = void 0; | ||
| Object.freeze(cont); | ||
| } | ||
| }; | ||
| }; | ||
| /** | ||
| * @mixin | ||
| */ | ||
| var NodeFsHandler = class { | ||
| constructor(fsW) { | ||
| this.fsw = fsW; | ||
| this._boundHandleError = (error) => fsW._handleError(error); | ||
| } | ||
| /** | ||
| * Watch file for changes with fs_watchFile or fs_watch. | ||
| * @param path to file or dir | ||
| * @param listener on fs change | ||
| * @returns closer for the watcher instance | ||
| */ | ||
| _watchWithNodeFs(path$2, listener) { | ||
| const opts = this.fsw.options; | ||
| const directory = sysPath.dirname(path$2); | ||
| const basename$2 = sysPath.basename(path$2); | ||
| this.fsw._getWatchedDir(directory).add(basename$2); | ||
| const absolutePath = sysPath.resolve(path$2); | ||
| const options = { persistent: opts.persistent }; | ||
| if (!listener) listener = EMPTY_FN; | ||
| let closer; | ||
| if (opts.usePolling) { | ||
| options.interval = opts.interval !== opts.binaryInterval && isBinaryPath(basename$2) ? opts.binaryInterval : opts.interval; | ||
| closer = setFsWatchFileListener(path$2, absolutePath, options, { | ||
| listener, | ||
| rawEmitter: this.fsw._emitRaw | ||
| }); | ||
| } else closer = setFsWatchListener(path$2, absolutePath, options, { | ||
| listener, | ||
| errHandler: this._boundHandleError, | ||
| rawEmitter: this.fsw._emitRaw | ||
| }); | ||
| return closer; | ||
| } | ||
| /** | ||
| * Watch a file and emit add event if warranted. | ||
| * @returns closer for the watcher instance | ||
| */ | ||
| _handleFile(file, stats, initialAdd) { | ||
| if (this.fsw.closed) return; | ||
| const dirname$2 = sysPath.dirname(file); | ||
| const basename$2 = sysPath.basename(file); | ||
| const parent = this.fsw._getWatchedDir(dirname$2); | ||
| let prevStats = stats; | ||
| if (parent.has(basename$2)) return; | ||
| const listener = async (path$2, newStats) => { | ||
| if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return; | ||
| if (!newStats || newStats.mtimeMs === 0) try { | ||
| const newStats$1 = await stat$2(file); | ||
| if (this.fsw.closed) return; | ||
| const at = newStats$1.atimeMs; | ||
| const mt = newStats$1.mtimeMs; | ||
| if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats$1); | ||
| if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats$1.ino) { | ||
| this.fsw._closeFile(path$2); | ||
| prevStats = newStats$1; | ||
| const closer$1 = this._watchWithNodeFs(file, listener); | ||
| if (closer$1) this.fsw._addPathCloser(path$2, closer$1); | ||
| } else prevStats = newStats$1; | ||
| } catch (error) { | ||
| this.fsw._remove(dirname$2, basename$2); | ||
| } | ||
| else if (parent.has(basename$2)) { | ||
| const at = newStats.atimeMs; | ||
| const mt = newStats.mtimeMs; | ||
| if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats); | ||
| prevStats = newStats; | ||
| } | ||
| }; | ||
| const closer = this._watchWithNodeFs(file, listener); | ||
| if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) { | ||
| if (!this.fsw._throttle(EV.ADD, file, 0)) return; | ||
| this.fsw._emit(EV.ADD, file, stats); | ||
| } | ||
| return closer; | ||
| } | ||
| /** | ||
| * Handle symlinks encountered while reading a dir. | ||
| * @param entry returned by readdirp | ||
| * @param directory path of dir being read | ||
| * @param path of this item | ||
| * @param item basename of this item | ||
| * @returns true if no more processing is needed for this entry. | ||
| */ | ||
| async _handleSymlink(entry, directory, path$2, item) { | ||
| if (this.fsw.closed) return; | ||
| const full = entry.fullPath; | ||
| const dir = this.fsw._getWatchedDir(directory); | ||
| if (!this.fsw.options.followSymlinks) { | ||
| this.fsw._incrReadyCount(); | ||
| let linkPath; | ||
| try { | ||
| linkPath = await realpath$1(path$2); | ||
| } catch (e) { | ||
| this.fsw._emitReady(); | ||
| return true; | ||
| } | ||
| if (this.fsw.closed) return; | ||
| if (dir.has(item)) { | ||
| if (this.fsw._symlinkPaths.get(full) !== linkPath) { | ||
| this.fsw._symlinkPaths.set(full, linkPath); | ||
| this.fsw._emit(EV.CHANGE, path$2, entry.stats); | ||
| } | ||
| } else { | ||
| dir.add(item); | ||
| this.fsw._symlinkPaths.set(full, linkPath); | ||
| this.fsw._emit(EV.ADD, path$2, entry.stats); | ||
| } | ||
| this.fsw._emitReady(); | ||
| return true; | ||
| } | ||
| if (this.fsw._symlinkPaths.has(full)) return true; | ||
| this.fsw._symlinkPaths.set(full, true); | ||
| } | ||
| _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { | ||
| directory = sysPath.join(directory, ""); | ||
| throttler = this.fsw._throttle("readdir", directory, 1e3); | ||
| if (!throttler) return; | ||
| const previous = this.fsw._getWatchedDir(wh.path); | ||
| const current = /* @__PURE__ */ new Set(); | ||
| let stream = this.fsw._readdirp(directory, { | ||
| fileFilter: (entry) => wh.filterPath(entry), | ||
| directoryFilter: (entry) => wh.filterDir(entry) | ||
| }); | ||
| if (!stream) return; | ||
| stream.on(STR_DATA, async (entry) => { | ||
| if (this.fsw.closed) { | ||
| stream = void 0; | ||
| return; | ||
| } | ||
| const item = entry.path; | ||
| let path$2 = sysPath.join(directory, item); | ||
| current.add(item); | ||
| if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path$2, item)) return; | ||
| if (this.fsw.closed) { | ||
| stream = void 0; | ||
| return; | ||
| } | ||
| if (item === target || !target && !previous.has(item)) { | ||
| this.fsw._incrReadyCount(); | ||
| path$2 = sysPath.join(dir, sysPath.relative(dir, path$2)); | ||
| this._addToNodeFs(path$2, initialAdd, wh, depth + 1); | ||
| } | ||
| }).on(EV.ERROR, this._boundHandleError); | ||
| return new Promise((resolve$2, reject) => { | ||
| if (!stream) return reject(); | ||
| stream.once(STR_END, () => { | ||
| if (this.fsw.closed) { | ||
| stream = void 0; | ||
| return; | ||
| } | ||
| const wasThrottled = throttler ? throttler.clear() : false; | ||
| resolve$2(void 0); | ||
| previous.getChildren().filter((item) => { | ||
| return item !== directory && !current.has(item); | ||
| }).forEach((item) => { | ||
| this.fsw._remove(directory, item); | ||
| }); | ||
| stream = void 0; | ||
| if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler); | ||
| }); | ||
| }); | ||
| } | ||
| /** | ||
| * Read directory to add / remove files from `@watched` list and re-read it on change. | ||
| * @param dir fs path | ||
| * @param stats | ||
| * @param initialAdd | ||
| * @param depth relative to user-supplied path | ||
| * @param target child path targeted for watch | ||
| * @param wh Common watch helpers for this path | ||
| * @param realpath | ||
| * @returns closer for the watcher instance. | ||
| */ | ||
| async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath$2) { | ||
| const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir)); | ||
| const tracked = parentDir.has(sysPath.basename(dir)); | ||
| if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) this.fsw._emit(EV.ADD_DIR, dir, stats); | ||
| parentDir.add(sysPath.basename(dir)); | ||
| this.fsw._getWatchedDir(dir); | ||
| let throttler; | ||
| let closer; | ||
| const oDepth = this.fsw.options.depth; | ||
| if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath$2)) { | ||
| if (!target) { | ||
| await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); | ||
| if (this.fsw.closed) return; | ||
| } | ||
| closer = this._watchWithNodeFs(dir, (dirPath, stats$1) => { | ||
| if (stats$1 && stats$1.mtimeMs === 0) return; | ||
| this._handleRead(dirPath, false, wh, target, dir, depth, throttler); | ||
| }); | ||
| } | ||
| return closer; | ||
| } | ||
| /** | ||
| * Handle added file, directory, or glob pattern. | ||
| * Delegates call to _handleFile / _handleDir after checks. | ||
| * @param path to file or ir | ||
| * @param initialAdd was the file added at watch instantiation? | ||
| * @param priorWh depth relative to user-supplied path | ||
| * @param depth Child path actually targeted for watch | ||
| * @param target Child path actually targeted for watch | ||
| */ | ||
| async _addToNodeFs(path$2, initialAdd, priorWh, depth, target) { | ||
| const ready = this.fsw._emitReady; | ||
| if (this.fsw._isIgnored(path$2) || this.fsw.closed) { | ||
| ready(); | ||
| return false; | ||
| } | ||
| const wh = this.fsw._getWatchHelpers(path$2); | ||
| if (priorWh) { | ||
| wh.filterPath = (entry) => priorWh.filterPath(entry); | ||
| wh.filterDir = (entry) => priorWh.filterDir(entry); | ||
| } | ||
| try { | ||
| const stats = await statMethods[wh.statMethod](wh.watchPath); | ||
| if (this.fsw.closed) return; | ||
| if (this.fsw._isIgnored(wh.watchPath, stats)) { | ||
| ready(); | ||
| return false; | ||
| } | ||
| const follow = this.fsw.options.followSymlinks; | ||
| let closer; | ||
| if (stats.isDirectory()) { | ||
| const absPath = sysPath.resolve(path$2); | ||
| const targetPath = follow ? await realpath$1(path$2) : path$2; | ||
| if (this.fsw.closed) return; | ||
| closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); | ||
| if (this.fsw.closed) return; | ||
| if (absPath !== targetPath && targetPath !== void 0) this.fsw._symlinkPaths.set(absPath, targetPath); | ||
| } else if (stats.isSymbolicLink()) { | ||
| const targetPath = follow ? await realpath$1(path$2) : path$2; | ||
| if (this.fsw.closed) return; | ||
| const parent = sysPath.dirname(wh.watchPath); | ||
| this.fsw._getWatchedDir(parent).add(wh.watchPath); | ||
| this.fsw._emit(EV.ADD, wh.watchPath, stats); | ||
| closer = await this._handleDir(parent, stats, initialAdd, depth, path$2, wh, targetPath); | ||
| if (this.fsw.closed) return; | ||
| if (targetPath !== void 0) this.fsw._symlinkPaths.set(sysPath.resolve(path$2), targetPath); | ||
| } else closer = this._handleFile(wh.watchPath, stats, initialAdd); | ||
| ready(); | ||
| if (closer) this.fsw._addPathCloser(path$2, closer); | ||
| return false; | ||
| } catch (error) { | ||
| if (this.fsw._handleError(error)) { | ||
| ready(); | ||
| return path$2; | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| //#endregion | ||
| //#region node_modules/.pnpm/chokidar@4.0.3/node_modules/chokidar/esm/index.js | ||
| /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */ | ||
| const SLASH = "/"; | ||
| const SLASH_SLASH = "//"; | ||
| const ONE_DOT = "."; | ||
| const TWO_DOTS = ".."; | ||
| const STRING_TYPE = "string"; | ||
| const BACK_SLASH_RE = /\\/g; | ||
| const DOUBLE_SLASH_RE = /\/\//; | ||
| const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; | ||
| const REPLACER_RE = /^\.[/\\]/; | ||
| function arrify(item) { | ||
| return Array.isArray(item) ? item : [item]; | ||
| } | ||
| const isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp); | ||
| function createPattern(matcher) { | ||
| if (typeof matcher === "function") return matcher; | ||
| if (typeof matcher === "string") return (string) => matcher === string; | ||
| if (matcher instanceof RegExp) return (string) => matcher.test(string); | ||
| if (typeof matcher === "object" && matcher !== null) return (string) => { | ||
| if (matcher.path === string) return true; | ||
| if (matcher.recursive) { | ||
| const relative$2 = sysPath.relative(matcher.path, string); | ||
| if (!relative$2) return false; | ||
| return !relative$2.startsWith("..") && !sysPath.isAbsolute(relative$2); | ||
| } | ||
| return false; | ||
| }; | ||
| return () => false; | ||
| } | ||
| function normalizePath(path$2) { | ||
| if (typeof path$2 !== "string") throw new Error("string expected"); | ||
| path$2 = sysPath.normalize(path$2); | ||
| path$2 = path$2.replace(/\\/g, "/"); | ||
| let prepend = false; | ||
| if (path$2.startsWith("//")) prepend = true; | ||
| const DOUBLE_SLASH_RE$1 = /\/\//; | ||
| while (path$2.match(DOUBLE_SLASH_RE$1)) path$2 = path$2.replace(DOUBLE_SLASH_RE$1, "/"); | ||
| if (prepend) path$2 = "/" + path$2; | ||
| return path$2; | ||
| } | ||
| function matchPatterns(patterns, testString, stats) { | ||
| const path$2 = normalizePath(testString); | ||
| for (let index = 0; index < patterns.length; index++) { | ||
| const pattern = patterns[index]; | ||
| if (pattern(path$2, stats)) return true; | ||
| } | ||
| return false; | ||
| } | ||
| function anymatch(matchers, testString) { | ||
| if (matchers == null) throw new TypeError("anymatch: specify first argument"); | ||
| const patterns = arrify(matchers).map((matcher) => createPattern(matcher)); | ||
| if (testString == null) return (testString$1, stats) => { | ||
| return matchPatterns(patterns, testString$1, stats); | ||
| }; | ||
| return matchPatterns(patterns, testString); | ||
| } | ||
| const unifyPaths = (paths_) => { | ||
| const paths = arrify(paths_).flat(); | ||
| if (!paths.every((p) => typeof p === STRING_TYPE)) throw new TypeError(`Non-string provided as watch path: ${paths}`); | ||
| return paths.map(normalizePathToUnix); | ||
| }; | ||
| const toUnix = (string) => { | ||
| let str = string.replace(BACK_SLASH_RE, SLASH); | ||
| let prepend = false; | ||
| if (str.startsWith(SLASH_SLASH)) prepend = true; | ||
| while (str.match(DOUBLE_SLASH_RE)) str = str.replace(DOUBLE_SLASH_RE, SLASH); | ||
| if (prepend) str = SLASH + str; | ||
| return str; | ||
| }; | ||
| const normalizePathToUnix = (path$2) => toUnix(sysPath.normalize(toUnix(path$2))); | ||
| const normalizeIgnored = (cwd = "") => (path$2) => { | ||
| if (typeof path$2 === "string") return normalizePathToUnix(sysPath.isAbsolute(path$2) ? path$2 : sysPath.join(cwd, path$2)); | ||
| else return path$2; | ||
| }; | ||
| const getAbsolutePath = (path$2, cwd) => { | ||
| if (sysPath.isAbsolute(path$2)) return path$2; | ||
| return sysPath.join(cwd, path$2); | ||
| }; | ||
| const EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set()); | ||
| /** | ||
| * Directory entry. | ||
| */ | ||
| var DirEntry = class { | ||
| constructor(dir, removeWatcher) { | ||
| this.path = dir; | ||
| this._removeWatcher = removeWatcher; | ||
| this.items = /* @__PURE__ */ new Set(); | ||
| } | ||
| add(item) { | ||
| const { items } = this; | ||
| if (!items) return; | ||
| if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item); | ||
| } | ||
| async remove(item) { | ||
| const { items } = this; | ||
| if (!items) return; | ||
| items.delete(item); | ||
| if (items.size > 0) return; | ||
| const dir = this.path; | ||
| try { | ||
| await readdir$1(dir); | ||
| } catch (err) { | ||
| if (this._removeWatcher) this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir)); | ||
| } | ||
| } | ||
| has(item) { | ||
| const { items } = this; | ||
| if (!items) return; | ||
| return items.has(item); | ||
| } | ||
| getChildren() { | ||
| const { items } = this; | ||
| if (!items) return []; | ||
| return [...items.values()]; | ||
| } | ||
| dispose() { | ||
| this.items.clear(); | ||
| this.path = ""; | ||
| this._removeWatcher = EMPTY_FN; | ||
| this.items = EMPTY_SET; | ||
| Object.freeze(this); | ||
| } | ||
| }; | ||
| const STAT_METHOD_F = "stat"; | ||
| const STAT_METHOD_L = "lstat"; | ||
| var WatchHelper = class { | ||
| constructor(path$2, follow, fsw) { | ||
| this.fsw = fsw; | ||
| const watchPath = path$2; | ||
| this.path = path$2 = path$2.replace(REPLACER_RE, ""); | ||
| this.watchPath = watchPath; | ||
| this.fullWatchPath = sysPath.resolve(watchPath); | ||
| this.dirParts = []; | ||
| this.dirParts.forEach((parts) => { | ||
| if (parts.length > 1) parts.pop(); | ||
| }); | ||
| this.followSymlinks = follow; | ||
| this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; | ||
| } | ||
| entryPath(entry) { | ||
| return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, entry.fullPath)); | ||
| } | ||
| filterPath(entry) { | ||
| const { stats } = entry; | ||
| if (stats && stats.isSymbolicLink()) return this.filterDir(entry); | ||
| const resolvedPath = this.entryPath(entry); | ||
| return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats); | ||
| } | ||
| filterDir(entry) { | ||
| return this.fsw._isntIgnored(this.entryPath(entry), entry.stats); | ||
| } | ||
| }; | ||
| /** | ||
| * Watches files & directories for changes. Emitted events: | ||
| * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error` | ||
| * | ||
| * new FSWatcher() | ||
| * .add(directories) | ||
| * .on('add', path => log('File', path, 'was added')) | ||
| */ | ||
| var FSWatcher = class extends EventEmitter { | ||
| constructor(_opts = {}) { | ||
| super(); | ||
| this.closed = false; | ||
| this._closers = /* @__PURE__ */ new Map(); | ||
| this._ignoredPaths = /* @__PURE__ */ new Set(); | ||
| this._throttled = /* @__PURE__ */ new Map(); | ||
| this._streams = /* @__PURE__ */ new Set(); | ||
| this._symlinkPaths = /* @__PURE__ */ new Map(); | ||
| this._watched = /* @__PURE__ */ new Map(); | ||
| this._pendingWrites = /* @__PURE__ */ new Map(); | ||
| this._pendingUnlinks = /* @__PURE__ */ new Map(); | ||
| this._readyCount = 0; | ||
| this._readyEmitted = false; | ||
| const awf = _opts.awaitWriteFinish; | ||
| const DEF_AWF = { | ||
| stabilityThreshold: 2e3, | ||
| pollInterval: 100 | ||
| }; | ||
| const opts = { | ||
| persistent: true, | ||
| ignoreInitial: false, | ||
| ignorePermissionErrors: false, | ||
| interval: 100, | ||
| binaryInterval: 300, | ||
| followSymlinks: true, | ||
| usePolling: false, | ||
| atomic: true, | ||
| ..._opts, | ||
| ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]), | ||
| awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { | ||
| ...DEF_AWF, | ||
| ...awf | ||
| } : false | ||
| }; | ||
| if (isIBMi) opts.usePolling = true; | ||
| if (opts.atomic === void 0) opts.atomic = !opts.usePolling; | ||
| const envPoll = process.env.CHOKIDAR_USEPOLLING; | ||
| if (envPoll !== void 0) { | ||
| const envLower = envPoll.toLowerCase(); | ||
| if (envLower === "false" || envLower === "0") opts.usePolling = false; | ||
| else if (envLower === "true" || envLower === "1") opts.usePolling = true; | ||
| else opts.usePolling = !!envLower; | ||
| } | ||
| const envInterval = process.env.CHOKIDAR_INTERVAL; | ||
| if (envInterval) opts.interval = Number.parseInt(envInterval, 10); | ||
| let readyCalls = 0; | ||
| this._emitReady = () => { | ||
| readyCalls++; | ||
| if (readyCalls >= this._readyCount) { | ||
| this._emitReady = EMPTY_FN; | ||
| this._readyEmitted = true; | ||
| process.nextTick(() => this.emit(EVENTS.READY)); | ||
| } | ||
| }; | ||
| this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args); | ||
| this._boundRemove = this._remove.bind(this); | ||
| this.options = opts; | ||
| this._nodeFsHandler = new NodeFsHandler(this); | ||
| Object.freeze(opts); | ||
| } | ||
| _addIgnoredPath(matcher) { | ||
| if (isMatcherObject(matcher)) { | ||
| for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) return; | ||
| } | ||
| this._ignoredPaths.add(matcher); | ||
| } | ||
| _removeIgnoredPath(matcher) { | ||
| this._ignoredPaths.delete(matcher); | ||
| if (typeof matcher === "string") { | ||
| for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher) this._ignoredPaths.delete(ignored); | ||
| } | ||
| } | ||
| /** | ||
| * Adds paths to be watched on an existing FSWatcher instance. | ||
| * @param paths_ file or file list. Other arguments are unused | ||
| */ | ||
| add(paths_, _origAdd, _internal) { | ||
| const { cwd } = this.options; | ||
| this.closed = false; | ||
| this._closePromise = void 0; | ||
| let paths = unifyPaths(paths_); | ||
| if (cwd) paths = paths.map((path$2) => { | ||
| return getAbsolutePath(path$2, cwd); | ||
| }); | ||
| paths.forEach((path$2) => { | ||
| this._removeIgnoredPath(path$2); | ||
| }); | ||
| this._userIgnored = void 0; | ||
| if (!this._readyCount) this._readyCount = 0; | ||
| this._readyCount += paths.length; | ||
| Promise.all(paths.map(async (path$2) => { | ||
| const res = await this._nodeFsHandler._addToNodeFs(path$2, !_internal, void 0, 0, _origAdd); | ||
| if (res) this._emitReady(); | ||
| return res; | ||
| })).then((results) => { | ||
| if (this.closed) return; | ||
| results.forEach((item) => { | ||
| if (item) this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item)); | ||
| }); | ||
| }); | ||
| return this; | ||
| } | ||
| /** | ||
| * Close watchers or start ignoring events from specified paths. | ||
| */ | ||
| unwatch(paths_) { | ||
| if (this.closed) return this; | ||
| const paths = unifyPaths(paths_); | ||
| const { cwd } = this.options; | ||
| paths.forEach((path$2) => { | ||
| if (!sysPath.isAbsolute(path$2) && !this._closers.has(path$2)) { | ||
| if (cwd) path$2 = sysPath.join(cwd, path$2); | ||
| path$2 = sysPath.resolve(path$2); | ||
| } | ||
| this._closePath(path$2); | ||
| this._addIgnoredPath(path$2); | ||
| if (this._watched.has(path$2)) this._addIgnoredPath({ | ||
| path: path$2, | ||
| recursive: true | ||
| }); | ||
| this._userIgnored = void 0; | ||
| }); | ||
| return this; | ||
| } | ||
| /** | ||
| * Close watchers and remove all listeners from watched paths. | ||
| */ | ||
| close() { | ||
| if (this._closePromise) return this._closePromise; | ||
| this.closed = true; | ||
| this.removeAllListeners(); | ||
| const closers = []; | ||
| this._closers.forEach((closerList) => closerList.forEach((closer) => { | ||
| const promise = closer(); | ||
| if (promise instanceof Promise) closers.push(promise); | ||
| })); | ||
| this._streams.forEach((stream) => stream.destroy()); | ||
| this._userIgnored = void 0; | ||
| this._readyCount = 0; | ||
| this._readyEmitted = false; | ||
| this._watched.forEach((dirent) => dirent.dispose()); | ||
| this._closers.clear(); | ||
| this._watched.clear(); | ||
| this._streams.clear(); | ||
| this._symlinkPaths.clear(); | ||
| this._throttled.clear(); | ||
| this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve(); | ||
| return this._closePromise; | ||
| } | ||
| /** | ||
| * Expose list of watched paths | ||
| * @returns for chaining | ||
| */ | ||
| getWatched() { | ||
| const watchList = {}; | ||
| this._watched.forEach((entry, dir) => { | ||
| const index = (this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir) || ONE_DOT; | ||
| watchList[index] = entry.getChildren().sort(); | ||
| }); | ||
| return watchList; | ||
| } | ||
| emitWithAll(event, args) { | ||
| this.emit(event, ...args); | ||
| if (event !== EVENTS.ERROR) this.emit(EVENTS.ALL, event, ...args); | ||
| } | ||
| /** | ||
| * Normalize and emit events. | ||
| * Calling _emit DOES NOT MEAN emit() would be called! | ||
| * @param event Type of event | ||
| * @param path File or directory path | ||
| * @param stats arguments to be passed with event | ||
| * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag | ||
| */ | ||
| async _emit(event, path$2, stats) { | ||
| if (this.closed) return; | ||
| const opts = this.options; | ||
| if (isWindows) path$2 = sysPath.normalize(path$2); | ||
| if (opts.cwd) path$2 = sysPath.relative(opts.cwd, path$2); | ||
| const args = [path$2]; | ||
| if (stats != null) args.push(stats); | ||
| const awf = opts.awaitWriteFinish; | ||
| let pw; | ||
| if (awf && (pw = this._pendingWrites.get(path$2))) { | ||
| pw.lastChange = /* @__PURE__ */ new Date(); | ||
| return this; | ||
| } | ||
| if (opts.atomic) { | ||
| if (event === EVENTS.UNLINK) { | ||
| this._pendingUnlinks.set(path$2, [event, ...args]); | ||
| setTimeout(() => { | ||
| this._pendingUnlinks.forEach((entry, path$3) => { | ||
| this.emit(...entry); | ||
| this.emit(EVENTS.ALL, ...entry); | ||
| this._pendingUnlinks.delete(path$3); | ||
| }); | ||
| }, typeof opts.atomic === "number" ? opts.atomic : 100); | ||
| return this; | ||
| } | ||
| if (event === EVENTS.ADD && this._pendingUnlinks.has(path$2)) { | ||
| event = EVENTS.CHANGE; | ||
| this._pendingUnlinks.delete(path$2); | ||
| } | ||
| } | ||
| if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) { | ||
| const awfEmit = (err, stats$1) => { | ||
| if (err) { | ||
| event = EVENTS.ERROR; | ||
| args[0] = err; | ||
| this.emitWithAll(event, args); | ||
| } else if (stats$1) { | ||
| if (args.length > 1) args[1] = stats$1; | ||
| else args.push(stats$1); | ||
| this.emitWithAll(event, args); | ||
| } | ||
| }; | ||
| this._awaitWriteFinish(path$2, awf.stabilityThreshold, event, awfEmit); | ||
| return this; | ||
| } | ||
| if (event === EVENTS.CHANGE) { | ||
| if (!this._throttle(EVENTS.CHANGE, path$2, 50)) return this; | ||
| } | ||
| if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) { | ||
| const fullPath = opts.cwd ? sysPath.join(opts.cwd, path$2) : path$2; | ||
| let stats$1; | ||
| try { | ||
| stats$1 = await stat$2(fullPath); | ||
| } catch (err) {} | ||
| if (!stats$1 || this.closed) return; | ||
| args.push(stats$1); | ||
| } | ||
| this.emitWithAll(event, args); | ||
| return this; | ||
| } | ||
| /** | ||
| * Common handler for errors | ||
| * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag | ||
| */ | ||
| _handleError(error) { | ||
| const code = error && error.code; | ||
| if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) this.emit(EVENTS.ERROR, error); | ||
| return error || this.closed; | ||
| } | ||
| /** | ||
| * Helper utility for throttling | ||
| * @param actionType type being throttled | ||
| * @param path being acted upon | ||
| * @param timeout duration of time to suppress duplicate actions | ||
| * @returns tracking object or false if action should be suppressed | ||
| */ | ||
| _throttle(actionType, path$2, timeout) { | ||
| if (!this._throttled.has(actionType)) this._throttled.set(actionType, /* @__PURE__ */ new Map()); | ||
| const action = this._throttled.get(actionType); | ||
| if (!action) throw new Error("invalid throttle"); | ||
| const actionPath = action.get(path$2); | ||
| if (actionPath) { | ||
| actionPath.count++; | ||
| return false; | ||
| } | ||
| let timeoutObject; | ||
| const clear = () => { | ||
| const item = action.get(path$2); | ||
| const count = item ? item.count : 0; | ||
| action.delete(path$2); | ||
| clearTimeout(timeoutObject); | ||
| if (item) clearTimeout(item.timeoutObject); | ||
| return count; | ||
| }; | ||
| timeoutObject = setTimeout(clear, timeout); | ||
| const thr = { | ||
| timeoutObject, | ||
| clear, | ||
| count: 0 | ||
| }; | ||
| action.set(path$2, thr); | ||
| return thr; | ||
| } | ||
| _incrReadyCount() { | ||
| return this._readyCount++; | ||
| } | ||
| /** | ||
| * Awaits write operation to finish. | ||
| * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. | ||
| * @param path being acted upon | ||
| * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished | ||
| * @param event | ||
| * @param awfEmit Callback to be called when ready for event to be emitted. | ||
| */ | ||
| _awaitWriteFinish(path$2, threshold, event, awfEmit) { | ||
| const awf = this.options.awaitWriteFinish; | ||
| if (typeof awf !== "object") return; | ||
| const pollInterval = awf.pollInterval; | ||
| let timeoutHandler; | ||
| let fullPath = path$2; | ||
| if (this.options.cwd && !sysPath.isAbsolute(path$2)) fullPath = sysPath.join(this.options.cwd, path$2); | ||
| const now = /* @__PURE__ */ new Date(); | ||
| const writes = this._pendingWrites; | ||
| function awaitWriteFinishFn(prevStat) { | ||
| stat$1(fullPath, (err, curStat) => { | ||
| if (err || !writes.has(path$2)) { | ||
| if (err && err.code !== "ENOENT") awfEmit(err); | ||
| return; | ||
| } | ||
| const now$1 = Number(/* @__PURE__ */ new Date()); | ||
| if (prevStat && curStat.size !== prevStat.size) writes.get(path$2).lastChange = now$1; | ||
| if (now$1 - writes.get(path$2).lastChange >= threshold) { | ||
| writes.delete(path$2); | ||
| awfEmit(void 0, curStat); | ||
| } else timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat); | ||
| }); | ||
| } | ||
| if (!writes.has(path$2)) { | ||
| writes.set(path$2, { | ||
| lastChange: now, | ||
| cancelWait: () => { | ||
| writes.delete(path$2); | ||
| clearTimeout(timeoutHandler); | ||
| return event; | ||
| } | ||
| }); | ||
| timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval); | ||
| } | ||
| } | ||
| /** | ||
| * Determines whether user has asked to ignore this path. | ||
| */ | ||
| _isIgnored(path$2, stats) { | ||
| if (this.options.atomic && DOT_RE.test(path$2)) return true; | ||
| if (!this._userIgnored) { | ||
| const { cwd } = this.options; | ||
| const ignored = (this.options.ignored || []).map(normalizeIgnored(cwd)); | ||
| this._userIgnored = anymatch([...[...this._ignoredPaths].map(normalizeIgnored(cwd)), ...ignored], void 0); | ||
| } | ||
| return this._userIgnored(path$2, stats); | ||
| } | ||
| _isntIgnored(path$2, stat$3) { | ||
| return !this._isIgnored(path$2, stat$3); | ||
| } | ||
| /** | ||
| * Provides a set of common helpers and properties relating to symlink handling. | ||
| * @param path file or directory pattern being watched | ||
| */ | ||
| _getWatchHelpers(path$2) { | ||
| return new WatchHelper(path$2, this.options.followSymlinks, this); | ||
| } | ||
| /** | ||
| * Provides directory tracking objects | ||
| * @param directory path of the directory | ||
| */ | ||
| _getWatchedDir(directory) { | ||
| const dir = sysPath.resolve(directory); | ||
| if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove)); | ||
| return this._watched.get(dir); | ||
| } | ||
| /** | ||
| * Check for read permissions: https://stackoverflow.com/a/11781404/1358405 | ||
| */ | ||
| _hasReadPermissions(stats) { | ||
| if (this.options.ignorePermissionErrors) return true; | ||
| return Boolean(Number(stats.mode) & 256); | ||
| } | ||
| /** | ||
| * Handles emitting unlink events for | ||
| * files and directories, and via recursion, for | ||
| * files and directories within directories that are unlinked | ||
| * @param directory within which the following item is located | ||
| * @param item base path of item/directory | ||
| */ | ||
| _remove(directory, item, isDirectory) { | ||
| const path$2 = sysPath.join(directory, item); | ||
| const fullPath = sysPath.resolve(path$2); | ||
| isDirectory = isDirectory != null ? isDirectory : this._watched.has(path$2) || this._watched.has(fullPath); | ||
| if (!this._throttle("remove", path$2, 100)) return; | ||
| if (!isDirectory && this._watched.size === 1) this.add(directory, item, true); | ||
| this._getWatchedDir(path$2).getChildren().forEach((nested) => this._remove(path$2, nested)); | ||
| const parent = this._getWatchedDir(directory); | ||
| const wasTracked = parent.has(item); | ||
| parent.remove(item); | ||
| if (this._symlinkPaths.has(fullPath)) this._symlinkPaths.delete(fullPath); | ||
| let relPath = path$2; | ||
| if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path$2); | ||
| if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { | ||
| if (this._pendingWrites.get(relPath).cancelWait() === EVENTS.ADD) return; | ||
| } | ||
| this._watched.delete(path$2); | ||
| this._watched.delete(fullPath); | ||
| const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK; | ||
| if (wasTracked && !this._isIgnored(path$2)) this._emit(eventName, path$2); | ||
| this._closePath(path$2); | ||
| } | ||
| /** | ||
| * Closes all watchers for a path | ||
| */ | ||
| _closePath(path$2) { | ||
| this._closeFile(path$2); | ||
| const dir = sysPath.dirname(path$2); | ||
| this._getWatchedDir(dir).remove(sysPath.basename(path$2)); | ||
| } | ||
| /** | ||
| * Closes only file-specific watchers | ||
| */ | ||
| _closeFile(path$2) { | ||
| const closers = this._closers.get(path$2); | ||
| if (!closers) return; | ||
| closers.forEach((closer) => closer()); | ||
| this._closers.delete(path$2); | ||
| } | ||
| _addPathCloser(path$2, closer) { | ||
| if (!closer) return; | ||
| let list = this._closers.get(path$2); | ||
| if (!list) { | ||
| list = []; | ||
| this._closers.set(path$2, list); | ||
| } | ||
| list.push(closer); | ||
| } | ||
| _readdirp(root, opts) { | ||
| if (this.closed) return; | ||
| let stream = readdirp(root, { | ||
| type: EVENTS.ALL, | ||
| alwaysStat: true, | ||
| lstat: true, | ||
| ...opts, | ||
| depth: 0 | ||
| }); | ||
| this._streams.add(stream); | ||
| stream.once(STR_CLOSE, () => { | ||
| stream = void 0; | ||
| }); | ||
| stream.once(STR_END, () => { | ||
| if (stream) { | ||
| this._streams.delete(stream); | ||
| stream = void 0; | ||
| } | ||
| }); | ||
| return stream; | ||
| } | ||
| }; | ||
| /** | ||
| * Instantiates watcher with paths to be tracked. | ||
| * @param paths file / directory paths | ||
| * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others | ||
| * @returns an instance of FSWatcher for chaining. | ||
| * @example | ||
| * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); }); | ||
| * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') }) | ||
| */ | ||
| function watch$1(paths, options = {}) { | ||
| const watcher = new FSWatcher(options); | ||
| watcher.add(paths); | ||
| return watcher; | ||
| } | ||
| var esm_default = { | ||
| watch: watch$1, | ||
| FSWatcher | ||
| }; | ||
| //#endregion | ||
| export { watch$1 as i, WatchHelper as n, esm_default as r, FSWatcher as t }; |
| import { n as __require, t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| //#region node_modules/.pnpm/commondir@1.0.1/node_modules/commondir/index.js | ||
| var require_commondir = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/commondir@1.0.1/node_modules/commondir/index.js": ((exports, module) => { | ||
| var path = __require("path"); | ||
| module.exports = function(basedir, relfiles) { | ||
| if (relfiles) var files = relfiles.map(function(r) { | ||
| return path.resolve(basedir, r); | ||
| }); | ||
| else var files = basedir; | ||
| var res = files.slice(1).reduce(function(ps, file) { | ||
| if (!file.match(/^([A-Za-z]:)?\/|\\/)) throw new Error("relative path without a basedir"); | ||
| var xs = file.split(/\/+|\\+/); | ||
| for (var i = 0; ps[i] === xs[i] && i < Math.min(ps.length, xs.length); i++); | ||
| return ps.slice(0, i); | ||
| }, files[0].split(/\/+|\\+/)); | ||
| return res.length > 1 ? res.join("/") : "/"; | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| export { require_commondir as t }; |
| import { t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| //#region node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js | ||
| var require_cjs = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js": ((exports, module) => { | ||
| var isMergeableObject = function isMergeableObject$1(value) { | ||
| return isNonNullObject(value) && !isSpecial(value); | ||
| }; | ||
| function isNonNullObject(value) { | ||
| return !!value && typeof value === "object"; | ||
| } | ||
| function isSpecial(value) { | ||
| var stringValue = Object.prototype.toString.call(value); | ||
| return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value); | ||
| } | ||
| var REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol.for ? Symbol.for("react.element") : 60103; | ||
| function isReactElement(value) { | ||
| return value.$$typeof === REACT_ELEMENT_TYPE; | ||
| } | ||
| function emptyTarget(val) { | ||
| return Array.isArray(val) ? [] : {}; | ||
| } | ||
| function cloneUnlessOtherwiseSpecified(value, options) { | ||
| return options.clone !== false && options.isMergeableObject(value) ? deepmerge(emptyTarget(value), value, options) : value; | ||
| } | ||
| function defaultArrayMerge(target, source, options) { | ||
| return target.concat(source).map(function(element) { | ||
| return cloneUnlessOtherwiseSpecified(element, options); | ||
| }); | ||
| } | ||
| function getMergeFunction(key, options) { | ||
| if (!options.customMerge) return deepmerge; | ||
| var customMerge = options.customMerge(key); | ||
| return typeof customMerge === "function" ? customMerge : deepmerge; | ||
| } | ||
| function getEnumerableOwnPropertySymbols(target) { | ||
| return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) { | ||
| return Object.propertyIsEnumerable.call(target, symbol); | ||
| }) : []; | ||
| } | ||
| function getKeys(target) { | ||
| return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)); | ||
| } | ||
| function propertyIsOnObject(object, property) { | ||
| try { | ||
| return property in object; | ||
| } catch (_) { | ||
| return false; | ||
| } | ||
| } | ||
| function propertyIsUnsafe(target, key) { | ||
| return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key)); | ||
| } | ||
| function mergeObject(target, source, options) { | ||
| var destination = {}; | ||
| if (options.isMergeableObject(target)) getKeys(target).forEach(function(key) { | ||
| destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); | ||
| }); | ||
| getKeys(source).forEach(function(key) { | ||
| if (propertyIsUnsafe(target, key)) return; | ||
| if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) destination[key] = getMergeFunction(key, options)(target[key], source[key], options); | ||
| else destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); | ||
| }); | ||
| return destination; | ||
| } | ||
| function deepmerge(target, source, options) { | ||
| options = options || {}; | ||
| options.arrayMerge = options.arrayMerge || defaultArrayMerge; | ||
| options.isMergeableObject = options.isMergeableObject || isMergeableObject; | ||
| options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; | ||
| var sourceIsArray = Array.isArray(source); | ||
| if (!(sourceIsArray === Array.isArray(target))) return cloneUnlessOtherwiseSpecified(source, options); | ||
| else if (sourceIsArray) return options.arrayMerge(target, source, options); | ||
| else return mergeObject(target, source, options); | ||
| } | ||
| deepmerge.all = function deepmergeAll(array, options) { | ||
| if (!Array.isArray(array)) throw new Error("first argument should be an array"); | ||
| return array.reduce(function(prev, next) { | ||
| return deepmerge(prev, next, options); | ||
| }, {}); | ||
| }; | ||
| var deepmerge_1 = deepmerge; | ||
| module.exports = deepmerge_1; | ||
| }) }); | ||
| //#endregion | ||
| export { require_cjs as t }; |
| //#region node_modules/.pnpm/dot-prop@10.1.0/node_modules/dot-prop/index.js | ||
| const isObject = (value) => { | ||
| const type = typeof value; | ||
| return value !== null && (type === "object" || type === "function"); | ||
| }; | ||
| const disallowedKeys = new Set([ | ||
| "__proto__", | ||
| "prototype", | ||
| "constructor" | ||
| ]); | ||
| const MAX_ARRAY_INDEX = 1e6; | ||
| const isDigit = (character) => character >= "0" && character <= "9"; | ||
| function shouldCoerceToNumber(segment) { | ||
| if (segment === "0") return true; | ||
| if (/^[1-9]\d*$/.test(segment)) { | ||
| const parsedNumber = Number.parseInt(segment, 10); | ||
| return parsedNumber <= Number.MAX_SAFE_INTEGER && parsedNumber <= MAX_ARRAY_INDEX; | ||
| } | ||
| return false; | ||
| } | ||
| function processSegment(segment, parts) { | ||
| if (disallowedKeys.has(segment)) return false; | ||
| if (segment && shouldCoerceToNumber(segment)) parts.push(Number.parseInt(segment, 10)); | ||
| else parts.push(segment); | ||
| return true; | ||
| } | ||
| function parsePath(path) { | ||
| if (typeof path !== "string") throw new TypeError(`Expected a string, got ${typeof path}`); | ||
| const parts = []; | ||
| let currentSegment = ""; | ||
| let currentPart = "start"; | ||
| let isEscaping = false; | ||
| let position = 0; | ||
| for (const character of path) { | ||
| position++; | ||
| if (isEscaping) { | ||
| currentSegment += character; | ||
| isEscaping = false; | ||
| continue; | ||
| } | ||
| if (character === "\\") { | ||
| if (currentPart === "index") throw new Error(`Invalid character '${character}' in an index at position ${position}`); | ||
| if (currentPart === "indexEnd") throw new Error(`Invalid character '${character}' after an index at position ${position}`); | ||
| isEscaping = true; | ||
| currentPart = currentPart === "start" ? "property" : currentPart; | ||
| continue; | ||
| } | ||
| switch (character) { | ||
| case ".": | ||
| if (currentPart === "index") throw new Error(`Invalid character '${character}' in an index at position ${position}`); | ||
| if (currentPart === "indexEnd") { | ||
| currentPart = "property"; | ||
| break; | ||
| } | ||
| if (!processSegment(currentSegment, parts)) return []; | ||
| currentSegment = ""; | ||
| currentPart = "property"; | ||
| break; | ||
| case "[": | ||
| if (currentPart === "index") throw new Error(`Invalid character '${character}' in an index at position ${position}`); | ||
| if (currentPart === "indexEnd") { | ||
| currentPart = "index"; | ||
| break; | ||
| } | ||
| if (currentPart === "property" || currentPart === "start") { | ||
| if ((currentSegment || currentPart === "property") && !processSegment(currentSegment, parts)) return []; | ||
| currentSegment = ""; | ||
| } | ||
| currentPart = "index"; | ||
| break; | ||
| case "]": | ||
| if (currentPart === "index") { | ||
| if (currentSegment === "") { | ||
| currentSegment = (parts.pop() || "") + "[]"; | ||
| currentPart = "property"; | ||
| } else { | ||
| const parsedNumber = Number.parseInt(currentSegment, 10); | ||
| if (!Number.isNaN(parsedNumber) && Number.isFinite(parsedNumber) && parsedNumber >= 0 && parsedNumber <= Number.MAX_SAFE_INTEGER && parsedNumber <= MAX_ARRAY_INDEX && currentSegment === String(parsedNumber)) parts.push(parsedNumber); | ||
| else parts.push(currentSegment); | ||
| currentSegment = ""; | ||
| currentPart = "indexEnd"; | ||
| } | ||
| break; | ||
| } | ||
| if (currentPart === "indexEnd") throw new Error(`Invalid character '${character}' after an index at position ${position}`); | ||
| currentSegment += character; | ||
| break; | ||
| default: | ||
| if (currentPart === "index" && !isDigit(character)) throw new Error(`Invalid character '${character}' in an index at position ${position}`); | ||
| if (currentPart === "indexEnd") throw new Error(`Invalid character '${character}' after an index at position ${position}`); | ||
| if (currentPart === "start") currentPart = "property"; | ||
| currentSegment += character; | ||
| } | ||
| } | ||
| if (isEscaping) currentSegment += "\\"; | ||
| switch (currentPart) { | ||
| case "property": | ||
| if (!processSegment(currentSegment, parts)) return []; | ||
| break; | ||
| case "index": throw new Error("Index was not closed"); | ||
| case "start": | ||
| parts.push(""); | ||
| break; | ||
| } | ||
| return parts; | ||
| } | ||
| function normalizePath(path) { | ||
| if (typeof path === "string") return parsePath(path); | ||
| if (Array.isArray(path)) { | ||
| const normalized = []; | ||
| for (const [index, segment] of path.entries()) { | ||
| if (typeof segment !== "string" && typeof segment !== "number") throw new TypeError(`Expected a string or number for path segment at index ${index}, got ${typeof segment}`); | ||
| if (typeof segment === "number" && !Number.isFinite(segment)) throw new TypeError(`Path segment at index ${index} must be a finite number, got ${segment}`); | ||
| if (disallowedKeys.has(segment)) return []; | ||
| if (typeof segment === "string" && shouldCoerceToNumber(segment)) normalized.push(Number.parseInt(segment, 10)); | ||
| else normalized.push(segment); | ||
| } | ||
| return normalized; | ||
| } | ||
| return []; | ||
| } | ||
| function getProperty(object, path, value) { | ||
| if (!isObject(object) || typeof path !== "string" && !Array.isArray(path)) return value === void 0 ? object : value; | ||
| const pathArray = normalizePath(path); | ||
| if (pathArray.length === 0) return value; | ||
| for (let index = 0; index < pathArray.length; index++) { | ||
| const key = pathArray[index]; | ||
| object = object[key]; | ||
| if (object === void 0 || object === null) { | ||
| if (index !== pathArray.length - 1) return value; | ||
| break; | ||
| } | ||
| } | ||
| return object === void 0 ? value : object; | ||
| } | ||
| //#endregion | ||
| export { getProperty as t }; |
| import { n as __require, t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| //#region node_modules/.pnpm/duplexer@0.1.2/node_modules/duplexer/index.js | ||
| var require_duplexer = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/duplexer@0.1.2/node_modules/duplexer/index.js": ((exports, module) => { | ||
| var Stream = __require("stream"); | ||
| var writeMethods = [ | ||
| "write", | ||
| "end", | ||
| "destroy" | ||
| ]; | ||
| var readMethods = ["resume", "pause"]; | ||
| var readEvents = ["data", "close"]; | ||
| var slice = Array.prototype.slice; | ||
| module.exports = duplex; | ||
| function forEach(arr, fn) { | ||
| if (arr.forEach) return arr.forEach(fn); | ||
| for (var i = 0; i < arr.length; i++) fn(arr[i], i); | ||
| } | ||
| function duplex(writer, reader) { | ||
| var stream = new Stream(); | ||
| var ended = false; | ||
| forEach(writeMethods, proxyWriter); | ||
| forEach(readMethods, proxyReader); | ||
| forEach(readEvents, proxyStream); | ||
| reader.on("end", handleEnd); | ||
| writer.on("drain", function() { | ||
| stream.emit("drain"); | ||
| }); | ||
| writer.on("error", reemit); | ||
| reader.on("error", reemit); | ||
| stream.writable = writer.writable; | ||
| stream.readable = reader.readable; | ||
| return stream; | ||
| function proxyWriter(methodName) { | ||
| stream[methodName] = method; | ||
| function method() { | ||
| return writer[methodName].apply(writer, arguments); | ||
| } | ||
| } | ||
| function proxyReader(methodName) { | ||
| stream[methodName] = method; | ||
| function method() { | ||
| stream.emit(methodName); | ||
| var func = reader[methodName]; | ||
| if (func) return func.apply(reader, arguments); | ||
| reader.emit(methodName); | ||
| } | ||
| } | ||
| function proxyStream(methodName) { | ||
| reader.on(methodName, reemit$1); | ||
| function reemit$1() { | ||
| var args = slice.call(arguments); | ||
| args.unshift(methodName); | ||
| stream.emit.apply(stream, args); | ||
| } | ||
| } | ||
| function handleEnd() { | ||
| if (ended) return; | ||
| ended = true; | ||
| var args = slice.call(arguments); | ||
| args.unshift("end"); | ||
| stream.emit.apply(stream, args); | ||
| } | ||
| function reemit(err) { | ||
| stream.emit("error", err); | ||
| } | ||
| } | ||
| }) }); | ||
| //#endregion | ||
| export { require_duplexer as t }; |
| import { n as __require, t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| //#region node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js | ||
| /*! | ||
| * etag | ||
| * Copyright(c) 2014-2016 Douglas Christopher Wilson | ||
| * MIT Licensed | ||
| */ | ||
| var require_etag = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js": ((exports, module) => { | ||
| /** | ||
| * Module exports. | ||
| * @public | ||
| */ | ||
| module.exports = etag; | ||
| /** | ||
| * Module dependencies. | ||
| * @private | ||
| */ | ||
| var crypto = __require("crypto"); | ||
| var Stats = __require("fs").Stats; | ||
| /** | ||
| * Module variables. | ||
| * @private | ||
| */ | ||
| var toString = Object.prototype.toString; | ||
| /** | ||
| * Generate an entity tag. | ||
| * | ||
| * @param {Buffer|string} entity | ||
| * @return {string} | ||
| * @private | ||
| */ | ||
| function entitytag(entity) { | ||
| if (entity.length === 0) return "\"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk\""; | ||
| var hash = crypto.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27); | ||
| return "\"" + (typeof entity === "string" ? Buffer.byteLength(entity, "utf8") : entity.length).toString(16) + "-" + hash + "\""; | ||
| } | ||
| /** | ||
| * Create a simple ETag. | ||
| * | ||
| * @param {string|Buffer|Stats} entity | ||
| * @param {object} [options] | ||
| * @param {boolean} [options.weak] | ||
| * @return {String} | ||
| * @public | ||
| */ | ||
| function etag(entity, options) { | ||
| if (entity == null) throw new TypeError("argument entity is required"); | ||
| var isStats = isstats(entity); | ||
| var weak = options && typeof options.weak === "boolean" ? options.weak : isStats; | ||
| if (!isStats && typeof entity !== "string" && !Buffer.isBuffer(entity)) throw new TypeError("argument entity must be string, Buffer, or fs.Stats"); | ||
| var tag = isStats ? stattag(entity) : entitytag(entity); | ||
| return weak ? "W/" + tag : tag; | ||
| } | ||
| /** | ||
| * Determine if object is a Stats object. | ||
| * | ||
| * @param {object} obj | ||
| * @return {boolean} | ||
| * @api private | ||
| */ | ||
| function isstats(obj) { | ||
| if (typeof Stats === "function" && obj instanceof Stats) return true; | ||
| return obj && typeof obj === "object" && "ctime" in obj && toString.call(obj.ctime) === "[object Date]" && "mtime" in obj && toString.call(obj.mtime) === "[object Date]" && "ino" in obj && typeof obj.ino === "number" && "size" in obj && typeof obj.size === "number"; | ||
| } | ||
| /** | ||
| * Generate a tag for a stat. | ||
| * | ||
| * @param {object} stat | ||
| * @return {string} | ||
| * @private | ||
| */ | ||
| function stattag(stat) { | ||
| var mtime = stat.mtime.getTime().toString(16); | ||
| return "\"" + stat.size.toString(16) + "-" + mtime + "\""; | ||
| } | ||
| }) }); | ||
| //#endregion | ||
| export { require_etag as t }; |
| import * as nativeFs$1 from "fs"; | ||
| import { basename, dirname, normalize, relative, resolve, sep } from "path"; | ||
| import { createRequire } from "module"; | ||
| //#region node_modules/.pnpm/fdir@6.5.0_picomatch@4.0.3/node_modules/fdir/dist/index.mjs | ||
| var __require = /* @__PURE__ */ createRequire(import.meta.url); | ||
| function cleanPath(path$1) { | ||
| let normalized = normalize(path$1); | ||
| if (normalized.length > 1 && normalized[normalized.length - 1] === sep) normalized = normalized.substring(0, normalized.length - 1); | ||
| return normalized; | ||
| } | ||
| const SLASHES_REGEX = /[\\/]/g; | ||
| function convertSlashes(path$1, separator) { | ||
| return path$1.replace(SLASHES_REGEX, separator); | ||
| } | ||
| const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i; | ||
| function isRootDirectory(path$1) { | ||
| return path$1 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path$1); | ||
| } | ||
| function normalizePath(path$1, options) { | ||
| const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options; | ||
| const pathNeedsCleaning = process.platform === "win32" && path$1.includes("/") || path$1.startsWith("."); | ||
| if (resolvePaths) path$1 = resolve(path$1); | ||
| if (normalizePath$1 || pathNeedsCleaning) path$1 = cleanPath(path$1); | ||
| if (path$1 === ".") return ""; | ||
| return convertSlashes(path$1[path$1.length - 1] !== pathSeparator ? path$1 + pathSeparator : path$1, pathSeparator); | ||
| } | ||
| function joinPathWithBasePath(filename, directoryPath) { | ||
| return directoryPath + filename; | ||
| } | ||
| function joinPathWithRelativePath(root, options) { | ||
| return function(filename, directoryPath) { | ||
| if (directoryPath.startsWith(root)) return directoryPath.slice(root.length) + filename; | ||
| else return convertSlashes(relative(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename; | ||
| }; | ||
| } | ||
| function joinPath(filename) { | ||
| return filename; | ||
| } | ||
| function joinDirectoryPath(filename, directoryPath, separator) { | ||
| return directoryPath + filename + separator; | ||
| } | ||
| function build$7(root, options) { | ||
| const { relativePaths, includeBasePath } = options; | ||
| return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath; | ||
| } | ||
| function pushDirectoryWithRelativePath(root) { | ||
| return function(directoryPath, paths) { | ||
| paths.push(directoryPath.substring(root.length) || "."); | ||
| }; | ||
| } | ||
| function pushDirectoryFilterWithRelativePath(root) { | ||
| return function(directoryPath, paths, filters) { | ||
| const relativePath = directoryPath.substring(root.length) || "."; | ||
| if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath); | ||
| }; | ||
| } | ||
| const pushDirectory = (directoryPath, paths) => { | ||
| paths.push(directoryPath || "."); | ||
| }; | ||
| const pushDirectoryFilter = (directoryPath, paths, filters) => { | ||
| const path$1 = directoryPath || "."; | ||
| if (filters.every((filter) => filter(path$1, true))) paths.push(path$1); | ||
| }; | ||
| const empty$2 = () => {}; | ||
| function build$6(root, options) { | ||
| const { includeDirs, filters, relativePaths } = options; | ||
| if (!includeDirs) return empty$2; | ||
| if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root); | ||
| return filters && filters.length ? pushDirectoryFilter : pushDirectory; | ||
| } | ||
| const pushFileFilterAndCount = (filename, _paths, counts, filters) => { | ||
| if (filters.every((filter) => filter(filename, false))) counts.files++; | ||
| }; | ||
| const pushFileFilter = (filename, paths, _counts, filters) => { | ||
| if (filters.every((filter) => filter(filename, false))) paths.push(filename); | ||
| }; | ||
| const pushFileCount = (_filename, _paths, counts, _filters) => { | ||
| counts.files++; | ||
| }; | ||
| const pushFile = (filename, paths) => { | ||
| paths.push(filename); | ||
| }; | ||
| const empty$1 = () => {}; | ||
| function build$5(options) { | ||
| const { excludeFiles, filters, onlyCounts } = options; | ||
| if (excludeFiles) return empty$1; | ||
| if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter; | ||
| else if (onlyCounts) return pushFileCount; | ||
| else return pushFile; | ||
| } | ||
| const getArray = (paths) => { | ||
| return paths; | ||
| }; | ||
| const getArrayGroup = () => { | ||
| return [""].slice(0, 0); | ||
| }; | ||
| function build$4(options) { | ||
| return options.group ? getArrayGroup : getArray; | ||
| } | ||
| const groupFiles = (groups, directory, files) => { | ||
| groups.push({ | ||
| directory, | ||
| files, | ||
| dir: directory | ||
| }); | ||
| }; | ||
| const empty = () => {}; | ||
| function build$3(options) { | ||
| return options.group ? groupFiles : empty; | ||
| } | ||
| const resolveSymlinksAsync = function(path$1, state, callback$1) { | ||
| const { queue, fs, options: { suppressErrors } } = state; | ||
| queue.enqueue(); | ||
| fs.realpath(path$1, (error, resolvedPath) => { | ||
| if (error) return queue.dequeue(suppressErrors ? null : error, state); | ||
| fs.stat(resolvedPath, (error$1, stat$1) => { | ||
| if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state); | ||
| if (stat$1.isDirectory() && isRecursive(path$1, resolvedPath, state)) return queue.dequeue(null, state); | ||
| callback$1(stat$1, resolvedPath); | ||
| queue.dequeue(null, state); | ||
| }); | ||
| }); | ||
| }; | ||
| const resolveSymlinks = function(path$1, state, callback$1) { | ||
| const { queue, fs, options: { suppressErrors } } = state; | ||
| queue.enqueue(); | ||
| try { | ||
| const resolvedPath = fs.realpathSync(path$1); | ||
| const stat$1 = fs.statSync(resolvedPath); | ||
| if (stat$1.isDirectory() && isRecursive(path$1, resolvedPath, state)) return; | ||
| callback$1(stat$1, resolvedPath); | ||
| } catch (e) { | ||
| if (!suppressErrors) throw e; | ||
| } | ||
| }; | ||
| function build$2(options, isSynchronous) { | ||
| if (!options.resolveSymlinks || options.excludeSymlinks) return null; | ||
| return isSynchronous ? resolveSymlinks : resolveSymlinksAsync; | ||
| } | ||
| function isRecursive(path$1, resolved, state) { | ||
| if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state); | ||
| let parent = dirname(path$1); | ||
| let depth = 1; | ||
| while (parent !== state.root && depth < 2) { | ||
| const resolvedPath = state.symlinks.get(parent); | ||
| if (!!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath))) depth++; | ||
| else parent = dirname(parent); | ||
| } | ||
| state.symlinks.set(path$1, resolved); | ||
| return depth > 1; | ||
| } | ||
| function isRecursiveUsingRealPaths(resolved, state) { | ||
| return state.visited.includes(resolved + state.options.pathSeparator); | ||
| } | ||
| const onlyCountsSync = (state) => { | ||
| return state.counts; | ||
| }; | ||
| const groupsSync = (state) => { | ||
| return state.groups; | ||
| }; | ||
| const defaultSync = (state) => { | ||
| return state.paths; | ||
| }; | ||
| const limitFilesSync = (state) => { | ||
| return state.paths.slice(0, state.options.maxFiles); | ||
| }; | ||
| const onlyCountsAsync = (state, error, callback$1) => { | ||
| report(error, callback$1, state.counts, state.options.suppressErrors); | ||
| return null; | ||
| }; | ||
| const defaultAsync = (state, error, callback$1) => { | ||
| report(error, callback$1, state.paths, state.options.suppressErrors); | ||
| return null; | ||
| }; | ||
| const limitFilesAsync = (state, error, callback$1) => { | ||
| report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors); | ||
| return null; | ||
| }; | ||
| const groupsAsync = (state, error, callback$1) => { | ||
| report(error, callback$1, state.groups, state.options.suppressErrors); | ||
| return null; | ||
| }; | ||
| function report(error, callback$1, output, suppressErrors) { | ||
| if (error && !suppressErrors) callback$1(error, output); | ||
| else callback$1(null, output); | ||
| } | ||
| function build$1(options, isSynchronous) { | ||
| const { onlyCounts, group, maxFiles } = options; | ||
| if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync; | ||
| else if (group) return isSynchronous ? groupsSync : groupsAsync; | ||
| else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync; | ||
| else return isSynchronous ? defaultSync : defaultAsync; | ||
| } | ||
| const readdirOpts = { withFileTypes: true }; | ||
| const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => { | ||
| state.queue.enqueue(); | ||
| if (currentDepth < 0) return state.queue.dequeue(null, state); | ||
| const { fs } = state; | ||
| state.visited.push(crawlPath); | ||
| state.counts.directories++; | ||
| fs.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => { | ||
| callback$1(entries, directoryPath, currentDepth); | ||
| state.queue.dequeue(state.options.suppressErrors ? null : error, state); | ||
| }); | ||
| }; | ||
| const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => { | ||
| const { fs } = state; | ||
| if (currentDepth < 0) return; | ||
| state.visited.push(crawlPath); | ||
| state.counts.directories++; | ||
| let entries = []; | ||
| try { | ||
| entries = fs.readdirSync(crawlPath || ".", readdirOpts); | ||
| } catch (e) { | ||
| if (!state.options.suppressErrors) throw e; | ||
| } | ||
| callback$1(entries, directoryPath, currentDepth); | ||
| }; | ||
| function build(isSynchronous) { | ||
| return isSynchronous ? walkSync : walkAsync; | ||
| } | ||
| /** | ||
| * This is a custom stateless queue to track concurrent async fs calls. | ||
| * It increments a counter whenever a call is queued and decrements it | ||
| * as soon as it completes. When the counter hits 0, it calls onQueueEmpty. | ||
| */ | ||
| var Queue = class { | ||
| count = 0; | ||
| constructor(onQueueEmpty) { | ||
| this.onQueueEmpty = onQueueEmpty; | ||
| } | ||
| enqueue() { | ||
| this.count++; | ||
| return this.count; | ||
| } | ||
| dequeue(error, output) { | ||
| if (this.onQueueEmpty && (--this.count <= 0 || error)) { | ||
| this.onQueueEmpty(error, output); | ||
| if (error) { | ||
| output.controller.abort(); | ||
| this.onQueueEmpty = void 0; | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| var Counter = class { | ||
| _files = 0; | ||
| _directories = 0; | ||
| set files(num) { | ||
| this._files = num; | ||
| } | ||
| get files() { | ||
| return this._files; | ||
| } | ||
| set directories(num) { | ||
| this._directories = num; | ||
| } | ||
| get directories() { | ||
| return this._directories; | ||
| } | ||
| /** | ||
| * @deprecated use `directories` instead | ||
| */ | ||
| /* c8 ignore next 3 */ | ||
| get dirs() { | ||
| return this._directories; | ||
| } | ||
| }; | ||
| /** | ||
| * AbortController is not supported on Node 14 so we use this until we can drop | ||
| * support for Node 14. | ||
| */ | ||
| var Aborter = class { | ||
| aborted = false; | ||
| abort() { | ||
| this.aborted = true; | ||
| } | ||
| }; | ||
| var Walker = class { | ||
| root; | ||
| isSynchronous; | ||
| state; | ||
| joinPath; | ||
| pushDirectory; | ||
| pushFile; | ||
| getArray; | ||
| groupFiles; | ||
| resolveSymlink; | ||
| walkDirectory; | ||
| callbackInvoker; | ||
| constructor(root, options, callback$1) { | ||
| this.isSynchronous = !callback$1; | ||
| this.callbackInvoker = build$1(options, this.isSynchronous); | ||
| this.root = normalizePath(root, options); | ||
| this.state = { | ||
| root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1), | ||
| paths: [""].slice(0, 0), | ||
| groups: [], | ||
| counts: new Counter(), | ||
| options, | ||
| queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)), | ||
| symlinks: /* @__PURE__ */ new Map(), | ||
| visited: [""].slice(0, 0), | ||
| controller: new Aborter(), | ||
| fs: options.fs || nativeFs$1 | ||
| }; | ||
| this.joinPath = build$7(this.root, options); | ||
| this.pushDirectory = build$6(this.root, options); | ||
| this.pushFile = build$5(options); | ||
| this.getArray = build$4(options); | ||
| this.groupFiles = build$3(options); | ||
| this.resolveSymlink = build$2(options, this.isSynchronous); | ||
| this.walkDirectory = build(this.isSynchronous); | ||
| } | ||
| start() { | ||
| this.pushDirectory(this.root, this.state.paths, this.state.options.filters); | ||
| this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk); | ||
| return this.isSynchronous ? this.callbackInvoker(this.state, null) : null; | ||
| } | ||
| walk = (entries, directoryPath, depth) => { | ||
| const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state; | ||
| if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return; | ||
| const files = this.getArray(this.state.paths); | ||
| for (let i = 0; i < entries.length; ++i) { | ||
| const entry = entries[i]; | ||
| if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) { | ||
| const filename = this.joinPath(entry.name, directoryPath); | ||
| this.pushFile(filename, files, this.state.counts, filters); | ||
| } else if (entry.isDirectory()) { | ||
| let path$1 = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator); | ||
| if (exclude && exclude(entry.name, path$1)) continue; | ||
| this.pushDirectory(path$1, paths, filters); | ||
| this.walkDirectory(this.state, path$1, path$1, depth - 1, this.walk); | ||
| } else if (this.resolveSymlink && entry.isSymbolicLink()) { | ||
| let path$1 = joinPathWithBasePath(entry.name, directoryPath); | ||
| this.resolveSymlink(path$1, this.state, (stat$1, resolvedPath) => { | ||
| if (stat$1.isDirectory()) { | ||
| resolvedPath = normalizePath(resolvedPath, this.state.options); | ||
| if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path$1 + pathSeparator)) return; | ||
| this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path$1 + pathSeparator, depth - 1, this.walk); | ||
| } else { | ||
| resolvedPath = useRealPaths ? resolvedPath : path$1; | ||
| const filename = basename(resolvedPath); | ||
| const directoryPath$1 = normalizePath(dirname(resolvedPath), this.state.options); | ||
| resolvedPath = this.joinPath(filename, directoryPath$1); | ||
| this.pushFile(resolvedPath, files, this.state.counts, filters); | ||
| } | ||
| }); | ||
| } | ||
| } | ||
| this.groupFiles(this.state.groups, directoryPath, files); | ||
| }; | ||
| }; | ||
| function promise(root, options) { | ||
| return new Promise((resolve$1, reject) => { | ||
| callback(root, options, (err, output) => { | ||
| if (err) return reject(err); | ||
| resolve$1(output); | ||
| }); | ||
| }); | ||
| } | ||
| function callback(root, options, callback$1) { | ||
| new Walker(root, options, callback$1).start(); | ||
| } | ||
| function sync(root, options) { | ||
| return new Walker(root, options).start(); | ||
| } | ||
| var APIBuilder = class { | ||
| constructor(root, options) { | ||
| this.root = root; | ||
| this.options = options; | ||
| } | ||
| withPromise() { | ||
| return promise(this.root, this.options); | ||
| } | ||
| withCallback(cb) { | ||
| callback(this.root, this.options, cb); | ||
| } | ||
| sync() { | ||
| return sync(this.root, this.options); | ||
| } | ||
| }; | ||
| let pm = null; | ||
| /* c8 ignore next 6 */ | ||
| try { | ||
| __require.resolve("picomatch"); | ||
| pm = __require("picomatch"); | ||
| } catch {} | ||
| var Builder = class { | ||
| globCache = {}; | ||
| options = { | ||
| maxDepth: Infinity, | ||
| suppressErrors: true, | ||
| pathSeparator: sep, | ||
| filters: [] | ||
| }; | ||
| globFunction; | ||
| constructor(options) { | ||
| this.options = { | ||
| ...this.options, | ||
| ...options | ||
| }; | ||
| this.globFunction = this.options.globFunction; | ||
| } | ||
| group() { | ||
| this.options.group = true; | ||
| return this; | ||
| } | ||
| withPathSeparator(separator) { | ||
| this.options.pathSeparator = separator; | ||
| return this; | ||
| } | ||
| withBasePath() { | ||
| this.options.includeBasePath = true; | ||
| return this; | ||
| } | ||
| withRelativePaths() { | ||
| this.options.relativePaths = true; | ||
| return this; | ||
| } | ||
| withDirs() { | ||
| this.options.includeDirs = true; | ||
| return this; | ||
| } | ||
| withMaxDepth(depth) { | ||
| this.options.maxDepth = depth; | ||
| return this; | ||
| } | ||
| withMaxFiles(limit) { | ||
| this.options.maxFiles = limit; | ||
| return this; | ||
| } | ||
| withFullPaths() { | ||
| this.options.resolvePaths = true; | ||
| this.options.includeBasePath = true; | ||
| return this; | ||
| } | ||
| withErrors() { | ||
| this.options.suppressErrors = false; | ||
| return this; | ||
| } | ||
| withSymlinks({ resolvePaths = true } = {}) { | ||
| this.options.resolveSymlinks = true; | ||
| this.options.useRealPaths = resolvePaths; | ||
| return this.withFullPaths(); | ||
| } | ||
| withAbortSignal(signal) { | ||
| this.options.signal = signal; | ||
| return this; | ||
| } | ||
| normalize() { | ||
| this.options.normalizePath = true; | ||
| return this; | ||
| } | ||
| filter(predicate) { | ||
| this.options.filters.push(predicate); | ||
| return this; | ||
| } | ||
| onlyDirs() { | ||
| this.options.excludeFiles = true; | ||
| this.options.includeDirs = true; | ||
| return this; | ||
| } | ||
| exclude(predicate) { | ||
| this.options.exclude = predicate; | ||
| return this; | ||
| } | ||
| onlyCounts() { | ||
| this.options.onlyCounts = true; | ||
| return this; | ||
| } | ||
| crawl(root) { | ||
| return new APIBuilder(root || ".", this.options); | ||
| } | ||
| withGlobFunction(fn) { | ||
| this.globFunction = fn; | ||
| return this; | ||
| } | ||
| /** | ||
| * @deprecated Pass options using the constructor instead: | ||
| * ```ts | ||
| * new fdir(options).crawl("/path/to/root"); | ||
| * ``` | ||
| * This method will be removed in v7.0 | ||
| */ | ||
| /* c8 ignore next 4 */ | ||
| crawlWithOptions(root, options) { | ||
| this.options = { | ||
| ...this.options, | ||
| ...options | ||
| }; | ||
| return new APIBuilder(root || ".", this.options); | ||
| } | ||
| glob(...patterns) { | ||
| if (this.globFunction) return this.globWithOptions(patterns); | ||
| return this.globWithOptions(patterns, ...[{ dot: true }]); | ||
| } | ||
| globWithOptions(patterns, ...options) { | ||
| const globFn = this.globFunction || pm; | ||
| /* c8 ignore next 5 */ | ||
| if (!globFn) throw new Error("Please specify a glob function to use glob matching."); | ||
| var isMatch = this.globCache[patterns.join("\0")]; | ||
| if (!isMatch) { | ||
| isMatch = globFn(patterns, ...options); | ||
| this.globCache[patterns.join("\0")] = isMatch; | ||
| } | ||
| this.options.filters.push((path$1) => isMatch(path$1)); | ||
| return this; | ||
| } | ||
| }; | ||
| //#endregion | ||
| export { Builder as t }; |
| import { t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| //#region node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js | ||
| var require_implementation = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js": ((exports, module) => { | ||
| var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; | ||
| var toStr = Object.prototype.toString; | ||
| var max = Math.max; | ||
| var funcType = "[object Function]"; | ||
| var concatty = function concatty$1(a, b) { | ||
| var arr = []; | ||
| for (var i = 0; i < a.length; i += 1) arr[i] = a[i]; | ||
| for (var j = 0; j < b.length; j += 1) arr[j + a.length] = b[j]; | ||
| return arr; | ||
| }; | ||
| var slicy = function slicy$1(arrLike, offset) { | ||
| var arr = []; | ||
| for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) arr[j] = arrLike[i]; | ||
| return arr; | ||
| }; | ||
| var joiny = function(arr, joiner) { | ||
| var str = ""; | ||
| for (var i = 0; i < arr.length; i += 1) { | ||
| str += arr[i]; | ||
| if (i + 1 < arr.length) str += joiner; | ||
| } | ||
| return str; | ||
| }; | ||
| module.exports = function bind(that) { | ||
| var target = this; | ||
| if (typeof target !== "function" || toStr.apply(target) !== funcType) throw new TypeError(ERROR_MESSAGE + target); | ||
| var args = slicy(arguments, 1); | ||
| var bound; | ||
| var binder = function() { | ||
| if (this instanceof bound) { | ||
| var result = target.apply(this, concatty(args, arguments)); | ||
| if (Object(result) === result) return result; | ||
| return this; | ||
| } | ||
| return target.apply(that, concatty(args, arguments)); | ||
| }; | ||
| var boundLength = max(0, target.length - args.length); | ||
| var boundArgs = []; | ||
| for (var i = 0; i < boundLength; i++) boundArgs[i] = "$" + i; | ||
| bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); | ||
| if (target.prototype) { | ||
| var Empty = function Empty$1() {}; | ||
| Empty.prototype = target.prototype; | ||
| bound.prototype = new Empty(); | ||
| Empty.prototype = null; | ||
| } | ||
| return bound; | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js | ||
| var require_function_bind = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js": ((exports, module) => { | ||
| var implementation = require_implementation(); | ||
| module.exports = Function.prototype.bind || implementation; | ||
| }) }); | ||
| //#endregion | ||
| export { require_function_bind as t }; |
| //#region node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs | ||
| var comma = ",".charCodeAt(0); | ||
| var semicolon = ";".charCodeAt(0); | ||
| var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | ||
| var intToChar = new Uint8Array(64); | ||
| var charToInt = new Uint8Array(128); | ||
| for (let i = 0; i < chars.length; i++) { | ||
| const c = chars.charCodeAt(i); | ||
| intToChar[i] = c; | ||
| charToInt[c] = i; | ||
| } | ||
| function decodeInteger(reader, relative) { | ||
| let value = 0; | ||
| let shift = 0; | ||
| let integer = 0; | ||
| do { | ||
| integer = charToInt[reader.next()]; | ||
| value |= (integer & 31) << shift; | ||
| shift += 5; | ||
| } while (integer & 32); | ||
| const shouldNegate = value & 1; | ||
| value >>>= 1; | ||
| if (shouldNegate) value = -2147483648 | -value; | ||
| return relative + value; | ||
| } | ||
| function encodeInteger(builder, num, relative) { | ||
| let delta = num - relative; | ||
| delta = delta < 0 ? -delta << 1 | 1 : delta << 1; | ||
| do { | ||
| let clamped = delta & 31; | ||
| delta >>>= 5; | ||
| if (delta > 0) clamped |= 32; | ||
| builder.write(intToChar[clamped]); | ||
| } while (delta > 0); | ||
| return num; | ||
| } | ||
| function hasMoreVlq(reader, max) { | ||
| if (reader.pos >= max) return false; | ||
| return reader.peek() !== comma; | ||
| } | ||
| var bufLength = 1024 * 16; | ||
| var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) { | ||
| return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString(); | ||
| } } : { decode(buf) { | ||
| let out = ""; | ||
| for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]); | ||
| return out; | ||
| } }; | ||
| var StringWriter = class { | ||
| constructor() { | ||
| this.pos = 0; | ||
| this.out = ""; | ||
| this.buffer = new Uint8Array(bufLength); | ||
| } | ||
| write(v) { | ||
| const { buffer } = this; | ||
| buffer[this.pos++] = v; | ||
| if (this.pos === bufLength) { | ||
| this.out += td.decode(buffer); | ||
| this.pos = 0; | ||
| } | ||
| } | ||
| flush() { | ||
| const { buffer, out, pos } = this; | ||
| return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; | ||
| } | ||
| }; | ||
| var StringReader = class { | ||
| constructor(buffer) { | ||
| this.pos = 0; | ||
| this.buffer = buffer; | ||
| } | ||
| next() { | ||
| return this.buffer.charCodeAt(this.pos++); | ||
| } | ||
| peek() { | ||
| return this.buffer.charCodeAt(this.pos); | ||
| } | ||
| indexOf(char) { | ||
| const { buffer, pos } = this; | ||
| const idx = buffer.indexOf(char, pos); | ||
| return idx === -1 ? buffer.length : idx; | ||
| } | ||
| }; | ||
| function decode(mappings) { | ||
| const { length } = mappings; | ||
| const reader = new StringReader(mappings); | ||
| const decoded = []; | ||
| let genColumn = 0; | ||
| let sourcesIndex = 0; | ||
| let sourceLine = 0; | ||
| let sourceColumn = 0; | ||
| let namesIndex = 0; | ||
| do { | ||
| const semi = reader.indexOf(";"); | ||
| const line = []; | ||
| let sorted = true; | ||
| let lastCol = 0; | ||
| genColumn = 0; | ||
| while (reader.pos < semi) { | ||
| let seg; | ||
| genColumn = decodeInteger(reader, genColumn); | ||
| if (genColumn < lastCol) sorted = false; | ||
| lastCol = genColumn; | ||
| if (hasMoreVlq(reader, semi)) { | ||
| sourcesIndex = decodeInteger(reader, sourcesIndex); | ||
| sourceLine = decodeInteger(reader, sourceLine); | ||
| sourceColumn = decodeInteger(reader, sourceColumn); | ||
| if (hasMoreVlq(reader, semi)) { | ||
| namesIndex = decodeInteger(reader, namesIndex); | ||
| seg = [ | ||
| genColumn, | ||
| sourcesIndex, | ||
| sourceLine, | ||
| sourceColumn, | ||
| namesIndex | ||
| ]; | ||
| } else seg = [ | ||
| genColumn, | ||
| sourcesIndex, | ||
| sourceLine, | ||
| sourceColumn | ||
| ]; | ||
| } else seg = [genColumn]; | ||
| line.push(seg); | ||
| reader.pos++; | ||
| } | ||
| if (!sorted) sort(line); | ||
| decoded.push(line); | ||
| reader.pos = semi + 1; | ||
| } while (reader.pos <= length); | ||
| return decoded; | ||
| } | ||
| function sort(line) { | ||
| line.sort(sortComparator$1); | ||
| } | ||
| function sortComparator$1(a, b) { | ||
| return a[0] - b[0]; | ||
| } | ||
| function encode(decoded) { | ||
| const writer = new StringWriter(); | ||
| let sourcesIndex = 0; | ||
| let sourceLine = 0; | ||
| let sourceColumn = 0; | ||
| let namesIndex = 0; | ||
| for (let i = 0; i < decoded.length; i++) { | ||
| const line = decoded[i]; | ||
| if (i > 0) writer.write(semicolon); | ||
| if (line.length === 0) continue; | ||
| let genColumn = 0; | ||
| for (let j = 0; j < line.length; j++) { | ||
| const segment = line[j]; | ||
| if (j > 0) writer.write(comma); | ||
| genColumn = encodeInteger(writer, segment[0], genColumn); | ||
| if (segment.length === 1) continue; | ||
| sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); | ||
| sourceLine = encodeInteger(writer, segment[2], sourceLine); | ||
| sourceColumn = encodeInteger(writer, segment[3], sourceColumn); | ||
| if (segment.length === 4) continue; | ||
| namesIndex = encodeInteger(writer, segment[4], namesIndex); | ||
| } | ||
| } | ||
| return writer.flush(); | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs | ||
| const schemeRegex = /^[\w+.-]+:\/\//; | ||
| /** | ||
| * Matches the parts of a URL: | ||
| * 1. Scheme, including ":", guaranteed. | ||
| * 2. User/password, including "@", optional. | ||
| * 3. Host, guaranteed. | ||
| * 4. Port, including ":", optional. | ||
| * 5. Path, including "/", optional. | ||
| * 6. Query, including "?", optional. | ||
| * 7. Hash, including "#", optional. | ||
| */ | ||
| const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; | ||
| /** | ||
| * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start | ||
| * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). | ||
| * | ||
| * 1. Host, optional. | ||
| * 2. Path, which may include "/", guaranteed. | ||
| * 3. Query, including "?", optional. | ||
| * 4. Hash, including "#", optional. | ||
| */ | ||
| const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; | ||
| function isAbsoluteUrl(input) { | ||
| return schemeRegex.test(input); | ||
| } | ||
| function isSchemeRelativeUrl(input) { | ||
| return input.startsWith("//"); | ||
| } | ||
| function isAbsolutePath(input) { | ||
| return input.startsWith("/"); | ||
| } | ||
| function isFileUrl(input) { | ||
| return input.startsWith("file:"); | ||
| } | ||
| function isRelative(input) { | ||
| return /^[.?#]/.test(input); | ||
| } | ||
| function parseAbsoluteUrl(input) { | ||
| const match = urlRegex.exec(input); | ||
| return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || ""); | ||
| } | ||
| function parseFileUrl(input) { | ||
| const match = fileRegex.exec(input); | ||
| const path = match[2]; | ||
| return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || ""); | ||
| } | ||
| function makeUrl(scheme, user, host, port, path, query, hash) { | ||
| return { | ||
| scheme, | ||
| user, | ||
| host, | ||
| port, | ||
| path, | ||
| query, | ||
| hash, | ||
| type: 7 | ||
| }; | ||
| } | ||
| function parseUrl(input) { | ||
| if (isSchemeRelativeUrl(input)) { | ||
| const url$1 = parseAbsoluteUrl("http:" + input); | ||
| url$1.scheme = ""; | ||
| url$1.type = 6; | ||
| return url$1; | ||
| } | ||
| if (isAbsolutePath(input)) { | ||
| const url$1 = parseAbsoluteUrl("http://foo.com" + input); | ||
| url$1.scheme = ""; | ||
| url$1.host = ""; | ||
| url$1.type = 5; | ||
| return url$1; | ||
| } | ||
| if (isFileUrl(input)) return parseFileUrl(input); | ||
| if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input); | ||
| const url = parseAbsoluteUrl("http://foo.com/" + input); | ||
| url.scheme = ""; | ||
| url.host = ""; | ||
| url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1; | ||
| return url; | ||
| } | ||
| function stripPathFilename(path) { | ||
| if (path.endsWith("/..")) return path; | ||
| const index = path.lastIndexOf("/"); | ||
| return path.slice(0, index + 1); | ||
| } | ||
| function mergePaths(url, base) { | ||
| normalizePath(base, base.type); | ||
| if (url.path === "/") url.path = base.path; | ||
| else url.path = stripPathFilename(base.path) + url.path; | ||
| } | ||
| /** | ||
| * The path can have empty directories "//", unneeded parents "foo/..", or current directory | ||
| * "foo/.". We need to normalize to a standard representation. | ||
| */ | ||
| function normalizePath(url, type) { | ||
| const rel = type <= 4; | ||
| const pieces = url.path.split("/"); | ||
| let pointer = 1; | ||
| let positive = 0; | ||
| let addTrailingSlash = false; | ||
| for (let i = 1; i < pieces.length; i++) { | ||
| const piece = pieces[i]; | ||
| if (!piece) { | ||
| addTrailingSlash = true; | ||
| continue; | ||
| } | ||
| addTrailingSlash = false; | ||
| if (piece === ".") continue; | ||
| if (piece === "..") { | ||
| if (positive) { | ||
| addTrailingSlash = true; | ||
| positive--; | ||
| pointer--; | ||
| } else if (rel) pieces[pointer++] = piece; | ||
| continue; | ||
| } | ||
| pieces[pointer++] = piece; | ||
| positive++; | ||
| } | ||
| let path = ""; | ||
| for (let i = 1; i < pointer; i++) path += "/" + pieces[i]; | ||
| if (!path || addTrailingSlash && !path.endsWith("/..")) path += "/"; | ||
| url.path = path; | ||
| } | ||
| /** | ||
| * Attempts to resolve `input` URL/path relative to `base`. | ||
| */ | ||
| function resolve(input, base) { | ||
| if (!input && !base) return ""; | ||
| const url = parseUrl(input); | ||
| let inputType = url.type; | ||
| if (base && inputType !== 7) { | ||
| const baseUrl = parseUrl(base); | ||
| const baseType = baseUrl.type; | ||
| switch (inputType) { | ||
| case 1: url.hash = baseUrl.hash; | ||
| case 2: url.query = baseUrl.query; | ||
| case 3: | ||
| case 4: mergePaths(url, baseUrl); | ||
| case 5: | ||
| url.user = baseUrl.user; | ||
| url.host = baseUrl.host; | ||
| url.port = baseUrl.port; | ||
| case 6: url.scheme = baseUrl.scheme; | ||
| } | ||
| if (baseType > inputType) inputType = baseType; | ||
| } | ||
| normalizePath(url, inputType); | ||
| const queryHash = url.query + url.hash; | ||
| switch (inputType) { | ||
| case 2: | ||
| case 3: return queryHash; | ||
| case 4: { | ||
| const path = url.path.slice(1); | ||
| if (!path) return queryHash || "."; | ||
| if (isRelative(base || input) && !isRelative(path)) return "./" + path + queryHash; | ||
| return path + queryHash; | ||
| } | ||
| case 5: return url.path + queryHash; | ||
| default: return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash; | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs | ||
| function stripFilename(path) { | ||
| if (!path) return ""; | ||
| const index = path.lastIndexOf("/"); | ||
| return path.slice(0, index + 1); | ||
| } | ||
| function resolver(mapUrl, sourceRoot) { | ||
| const from = stripFilename(mapUrl); | ||
| const prefix = sourceRoot ? sourceRoot + "/" : ""; | ||
| return (source) => resolve(prefix + (source || ""), from); | ||
| } | ||
| var COLUMN$1 = 0; | ||
| function maybeSort(mappings, owned) { | ||
| const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); | ||
| if (unsortedIndex === mappings.length) return mappings; | ||
| if (!owned) mappings = mappings.slice(); | ||
| for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) mappings[i] = sortSegments(mappings[i], owned); | ||
| return mappings; | ||
| } | ||
| function nextUnsortedSegmentLine(mappings, start) { | ||
| for (let i = start; i < mappings.length; i++) if (!isSorted(mappings[i])) return i; | ||
| return mappings.length; | ||
| } | ||
| function isSorted(line) { | ||
| for (let j = 1; j < line.length; j++) if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) return false; | ||
| return true; | ||
| } | ||
| function sortSegments(line, owned) { | ||
| if (!owned) line = line.slice(); | ||
| return line.sort(sortComparator); | ||
| } | ||
| function sortComparator(a, b) { | ||
| return a[COLUMN$1] - b[COLUMN$1]; | ||
| } | ||
| var found = false; | ||
| function binarySearch(haystack, needle, low, high) { | ||
| while (low <= high) { | ||
| const mid = low + (high - low >> 1); | ||
| const cmp = haystack[mid][COLUMN$1] - needle; | ||
| if (cmp === 0) { | ||
| found = true; | ||
| return mid; | ||
| } | ||
| if (cmp < 0) low = mid + 1; | ||
| else high = mid - 1; | ||
| } | ||
| found = false; | ||
| return low - 1; | ||
| } | ||
| function upperBound(haystack, needle, index) { | ||
| for (let i = index + 1; i < haystack.length; index = i++) if (haystack[i][COLUMN$1] !== needle) break; | ||
| return index; | ||
| } | ||
| function lowerBound(haystack, needle, index) { | ||
| for (let i = index - 1; i >= 0; index = i--) if (haystack[i][COLUMN$1] !== needle) break; | ||
| return index; | ||
| } | ||
| function memoizedState() { | ||
| return { | ||
| lastKey: -1, | ||
| lastNeedle: -1, | ||
| lastIndex: -1 | ||
| }; | ||
| } | ||
| function memoizedBinarySearch(haystack, needle, state, key) { | ||
| const { lastKey, lastNeedle, lastIndex } = state; | ||
| let low = 0; | ||
| let high = haystack.length - 1; | ||
| if (key === lastKey) { | ||
| if (needle === lastNeedle) { | ||
| found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle; | ||
| return lastIndex; | ||
| } | ||
| if (needle >= lastNeedle) low = lastIndex === -1 ? 0 : lastIndex; | ||
| else high = lastIndex; | ||
| } | ||
| state.lastKey = key; | ||
| state.lastNeedle = needle; | ||
| return state.lastIndex = binarySearch(haystack, needle, low, high); | ||
| } | ||
| function parse(map) { | ||
| return typeof map === "string" ? JSON.parse(map) : map; | ||
| } | ||
| var LEAST_UPPER_BOUND = -1; | ||
| var GREATEST_LOWER_BOUND = 1; | ||
| var TraceMap = class { | ||
| constructor(map, mapUrl) { | ||
| const isString = typeof map === "string"; | ||
| if (!isString && map._decodedMemo) return map; | ||
| const parsed = parse(map); | ||
| const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; | ||
| this.version = version; | ||
| this.file = file; | ||
| this.names = names || []; | ||
| this.sourceRoot = sourceRoot; | ||
| this.sources = sources; | ||
| this.sourcesContent = sourcesContent; | ||
| this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0; | ||
| const resolve$1 = resolver(mapUrl, sourceRoot); | ||
| this.resolvedSources = sources.map(resolve$1); | ||
| const { mappings } = parsed; | ||
| if (typeof mappings === "string") { | ||
| this._encoded = mappings; | ||
| this._decoded = void 0; | ||
| } else if (Array.isArray(mappings)) { | ||
| this._encoded = void 0; | ||
| this._decoded = maybeSort(mappings, isString); | ||
| } else if (parsed.sections) throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`); | ||
| else throw new Error(`invalid source map: ${JSON.stringify(parsed)}`); | ||
| this._decodedMemo = memoizedState(); | ||
| this._bySources = void 0; | ||
| this._bySourceMemos = void 0; | ||
| } | ||
| }; | ||
| function cast$1(map) { | ||
| return map; | ||
| } | ||
| function decodedMappings(map) { | ||
| var _a; | ||
| return (_a = cast$1(map))._decoded || (_a._decoded = decode(cast$1(map)._encoded)); | ||
| } | ||
| function traceSegment(map, line, column) { | ||
| const decoded = decodedMappings(map); | ||
| if (line >= decoded.length) return null; | ||
| const segments = decoded[line]; | ||
| const index = traceSegmentInternal(segments, cast$1(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND); | ||
| return index === -1 ? null : segments[index]; | ||
| } | ||
| function traceSegmentInternal(segments, memo, line, column, bias) { | ||
| let index = memoizedBinarySearch(segments, column, memo, line); | ||
| if (found) index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); | ||
| else if (bias === LEAST_UPPER_BOUND) index++; | ||
| if (index === -1 || index === segments.length) return -1; | ||
| return index; | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs | ||
| var SetArray = class { | ||
| constructor() { | ||
| this._indexes = { __proto__: null }; | ||
| this.array = []; | ||
| } | ||
| }; | ||
| function cast(set) { | ||
| return set; | ||
| } | ||
| function get(setarr, key) { | ||
| return cast(setarr)._indexes[key]; | ||
| } | ||
| function put(setarr, key) { | ||
| const index = get(setarr, key); | ||
| if (index !== void 0) return index; | ||
| const { array, _indexes: indexes } = cast(setarr); | ||
| return indexes[key] = array.push(key) - 1; | ||
| } | ||
| function remove(setarr, key) { | ||
| const index = get(setarr, key); | ||
| if (index === void 0) return; | ||
| const { array, _indexes: indexes } = cast(setarr); | ||
| for (let i = index + 1; i < array.length; i++) { | ||
| const k = array[i]; | ||
| array[i - 1] = k; | ||
| indexes[k]--; | ||
| } | ||
| indexes[key] = void 0; | ||
| array.pop(); | ||
| } | ||
| var COLUMN = 0; | ||
| var SOURCES_INDEX = 1; | ||
| var SOURCE_LINE = 2; | ||
| var SOURCE_COLUMN = 3; | ||
| var NAMES_INDEX = 4; | ||
| var NO_NAME = -1; | ||
| var GenMapping = class { | ||
| constructor({ file, sourceRoot } = {}) { | ||
| this._names = new SetArray(); | ||
| this._sources = new SetArray(); | ||
| this._sourcesContent = []; | ||
| this._mappings = []; | ||
| this.file = file; | ||
| this.sourceRoot = sourceRoot; | ||
| this._ignoreList = new SetArray(); | ||
| } | ||
| }; | ||
| function cast2(map) { | ||
| return map; | ||
| } | ||
| var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { | ||
| return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); | ||
| }; | ||
| function setSourceContent(map, source, content) { | ||
| const { _sources: sources, _sourcesContent: sourcesContent } = cast2(map); | ||
| const index = put(sources, source); | ||
| sourcesContent[index] = content; | ||
| } | ||
| function setIgnore(map, source, ignore = true) { | ||
| const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast2(map); | ||
| const index = put(sources, source); | ||
| if (index === sourcesContent.length) sourcesContent[index] = null; | ||
| if (ignore) put(ignoreList, index); | ||
| else remove(ignoreList, index); | ||
| } | ||
| function toDecodedMap(map) { | ||
| const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast2(map); | ||
| removeEmptyFinalLines(mappings); | ||
| return { | ||
| version: 3, | ||
| file: map.file || void 0, | ||
| names: names.array, | ||
| sourceRoot: map.sourceRoot || void 0, | ||
| sources: sources.array, | ||
| sourcesContent, | ||
| mappings, | ||
| ignoreList: ignoreList.array | ||
| }; | ||
| } | ||
| function toEncodedMap(map) { | ||
| const decoded = toDecodedMap(map); | ||
| return Object.assign({}, decoded, { mappings: encode(decoded.mappings) }); | ||
| } | ||
| function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { | ||
| const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast2(map); | ||
| const line = getIndex(mappings, genLine); | ||
| const index = getColumnIndex(line, genColumn); | ||
| if (!source) { | ||
| if (skipable && skipSourceless(line, index)) return; | ||
| return insert(line, index, [genColumn]); | ||
| } | ||
| assert(sourceLine); | ||
| assert(sourceColumn); | ||
| const sourcesIndex = put(sources, source); | ||
| const namesIndex = name ? put(names, name) : NO_NAME; | ||
| if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null; | ||
| if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) return; | ||
| return insert(line, index, name ? [ | ||
| genColumn, | ||
| sourcesIndex, | ||
| sourceLine, | ||
| sourceColumn, | ||
| namesIndex | ||
| ] : [ | ||
| genColumn, | ||
| sourcesIndex, | ||
| sourceLine, | ||
| sourceColumn | ||
| ]); | ||
| } | ||
| function assert(_val) {} | ||
| function getIndex(arr, index) { | ||
| for (let i = arr.length; i <= index; i++) arr[i] = []; | ||
| return arr[index]; | ||
| } | ||
| function getColumnIndex(line, genColumn) { | ||
| let index = line.length; | ||
| for (let i = index - 1; i >= 0; index = i--) if (genColumn >= line[i][COLUMN]) break; | ||
| return index; | ||
| } | ||
| function insert(array, index, value) { | ||
| for (let i = array.length; i > index; i--) array[i] = array[i - 1]; | ||
| array[index] = value; | ||
| } | ||
| function removeEmptyFinalLines(mappings) { | ||
| const { length } = mappings; | ||
| let len = length; | ||
| for (let i = len - 1; i >= 0; len = i, i--) if (mappings[i].length > 0) break; | ||
| if (len < length) mappings.length = len; | ||
| } | ||
| function skipSourceless(line, index) { | ||
| if (index === 0) return true; | ||
| return line[index - 1].length === 1; | ||
| } | ||
| function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { | ||
| if (index === 0) return false; | ||
| const prev = line[index - 1]; | ||
| if (prev.length === 1) return false; | ||
| return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME); | ||
| } | ||
| //#endregion | ||
| export { toDecodedMap as a, decodedMappings as c, setSourceContent as i, traceSegment as l, maybeAddSegment as n, toEncodedMap as o, setIgnore as r, TraceMap as s, GenMapping as t, encode as u }; |
Sorry, the diff of this file is too big to display
| import { i as __toESM } from "../_chunks/Bqks5huO.mjs"; | ||
| import { t as require_duplexer } from "./duplexer.mjs"; | ||
| import fs from "node:fs"; | ||
| import { promisify } from "node:util"; | ||
| import zlib from "node:zlib"; | ||
| import "node:stream"; | ||
| //#region node_modules/.pnpm/gzip-size@7.0.0/node_modules/gzip-size/index.js | ||
| var import_duplexer = /* @__PURE__ */ __toESM(require_duplexer(), 1); | ||
| const getOptions = (options) => ({ | ||
| level: 9, | ||
| ...options | ||
| }); | ||
| const gzip = promisify(zlib.gzip); | ||
| async function gzipSize(input, options) { | ||
| if (!input) return 0; | ||
| return (await gzip(input, getOptions(options))).length; | ||
| } | ||
| //#endregion | ||
| export { gzipSize as t }; |
| import { t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| import { t as require_function_bind } from "./function-bind.mjs"; | ||
| //#region node_modules/.pnpm/hasown@2.0.2/node_modules/hasown/index.js | ||
| var require_hasown = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/hasown@2.0.2/node_modules/hasown/index.js": ((exports, module) => { | ||
| var call = Function.prototype.call; | ||
| var $hasOwn = Object.prototype.hasOwnProperty; | ||
| var bind = require_function_bind(); | ||
| /** @type {import('.')} */ | ||
| module.exports = bind.call(call, $hasOwn); | ||
| }) }); | ||
| //#endregion | ||
| export { require_hasown as t }; |
| import { t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| import { t as require_hasown } from "./hasown.mjs"; | ||
| //#region node_modules/.pnpm/is-core-module@2.16.1/node_modules/is-core-module/core.json | ||
| var require_core = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/is-core-module@2.16.1/node_modules/is-core-module/core.json": ((exports, module) => { | ||
| module.exports = { | ||
| "assert": true, | ||
| "node:assert": [">= 14.18 && < 15", ">= 16"], | ||
| "assert/strict": ">= 15", | ||
| "node:assert/strict": ">= 16", | ||
| "async_hooks": ">= 8", | ||
| "node:async_hooks": [">= 14.18 && < 15", ">= 16"], | ||
| "buffer_ieee754": ">= 0.5 && < 0.9.7", | ||
| "buffer": true, | ||
| "node:buffer": [">= 14.18 && < 15", ">= 16"], | ||
| "child_process": true, | ||
| "node:child_process": [">= 14.18 && < 15", ">= 16"], | ||
| "cluster": ">= 0.5", | ||
| "node:cluster": [">= 14.18 && < 15", ">= 16"], | ||
| "console": true, | ||
| "node:console": [">= 14.18 && < 15", ">= 16"], | ||
| "constants": true, | ||
| "node:constants": [">= 14.18 && < 15", ">= 16"], | ||
| "crypto": true, | ||
| "node:crypto": [">= 14.18 && < 15", ">= 16"], | ||
| "_debug_agent": ">= 1 && < 8", | ||
| "_debugger": "< 8", | ||
| "dgram": true, | ||
| "node:dgram": [">= 14.18 && < 15", ">= 16"], | ||
| "diagnostics_channel": [">= 14.17 && < 15", ">= 15.1"], | ||
| "node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"], | ||
| "dns": true, | ||
| "node:dns": [">= 14.18 && < 15", ">= 16"], | ||
| "dns/promises": ">= 15", | ||
| "node:dns/promises": ">= 16", | ||
| "domain": ">= 0.7.12", | ||
| "node:domain": [">= 14.18 && < 15", ">= 16"], | ||
| "events": true, | ||
| "node:events": [">= 14.18 && < 15", ">= 16"], | ||
| "freelist": "< 6", | ||
| "fs": true, | ||
| "node:fs": [">= 14.18 && < 15", ">= 16"], | ||
| "fs/promises": [">= 10 && < 10.1", ">= 14"], | ||
| "node:fs/promises": [">= 14.18 && < 15", ">= 16"], | ||
| "_http_agent": ">= 0.11.1", | ||
| "node:_http_agent": [">= 14.18 && < 15", ">= 16"], | ||
| "_http_client": ">= 0.11.1", | ||
| "node:_http_client": [">= 14.18 && < 15", ">= 16"], | ||
| "_http_common": ">= 0.11.1", | ||
| "node:_http_common": [">= 14.18 && < 15", ">= 16"], | ||
| "_http_incoming": ">= 0.11.1", | ||
| "node:_http_incoming": [">= 14.18 && < 15", ">= 16"], | ||
| "_http_outgoing": ">= 0.11.1", | ||
| "node:_http_outgoing": [">= 14.18 && < 15", ">= 16"], | ||
| "_http_server": ">= 0.11.1", | ||
| "node:_http_server": [">= 14.18 && < 15", ">= 16"], | ||
| "http": true, | ||
| "node:http": [">= 14.18 && < 15", ">= 16"], | ||
| "http2": ">= 8.8", | ||
| "node:http2": [">= 14.18 && < 15", ">= 16"], | ||
| "https": true, | ||
| "node:https": [">= 14.18 && < 15", ">= 16"], | ||
| "inspector": ">= 8", | ||
| "node:inspector": [">= 14.18 && < 15", ">= 16"], | ||
| "inspector/promises": [">= 19"], | ||
| "node:inspector/promises": [">= 19"], | ||
| "_linklist": "< 8", | ||
| "module": true, | ||
| "node:module": [">= 14.18 && < 15", ">= 16"], | ||
| "net": true, | ||
| "node:net": [">= 14.18 && < 15", ">= 16"], | ||
| "node-inspect/lib/_inspect": ">= 7.6 && < 12", | ||
| "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12", | ||
| "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12", | ||
| "os": true, | ||
| "node:os": [">= 14.18 && < 15", ">= 16"], | ||
| "path": true, | ||
| "node:path": [">= 14.18 && < 15", ">= 16"], | ||
| "path/posix": ">= 15.3", | ||
| "node:path/posix": ">= 16", | ||
| "path/win32": ">= 15.3", | ||
| "node:path/win32": ">= 16", | ||
| "perf_hooks": ">= 8.5", | ||
| "node:perf_hooks": [">= 14.18 && < 15", ">= 16"], | ||
| "process": ">= 1", | ||
| "node:process": [">= 14.18 && < 15", ">= 16"], | ||
| "punycode": ">= 0.5", | ||
| "node:punycode": [">= 14.18 && < 15", ">= 16"], | ||
| "querystring": true, | ||
| "node:querystring": [">= 14.18 && < 15", ">= 16"], | ||
| "readline": true, | ||
| "node:readline": [">= 14.18 && < 15", ">= 16"], | ||
| "readline/promises": ">= 17", | ||
| "node:readline/promises": ">= 17", | ||
| "repl": true, | ||
| "node:repl": [">= 14.18 && < 15", ">= 16"], | ||
| "node:sea": [">= 20.12 && < 21", ">= 21.7"], | ||
| "smalloc": ">= 0.11.5 && < 3", | ||
| "node:sqlite": [">= 22.13 && < 23", ">= 23.4"], | ||
| "_stream_duplex": ">= 0.9.4", | ||
| "node:_stream_duplex": [">= 14.18 && < 15", ">= 16"], | ||
| "_stream_transform": ">= 0.9.4", | ||
| "node:_stream_transform": [">= 14.18 && < 15", ">= 16"], | ||
| "_stream_wrap": ">= 1.4.1", | ||
| "node:_stream_wrap": [">= 14.18 && < 15", ">= 16"], | ||
| "_stream_passthrough": ">= 0.9.4", | ||
| "node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"], | ||
| "_stream_readable": ">= 0.9.4", | ||
| "node:_stream_readable": [">= 14.18 && < 15", ">= 16"], | ||
| "_stream_writable": ">= 0.9.4", | ||
| "node:_stream_writable": [">= 14.18 && < 15", ">= 16"], | ||
| "stream": true, | ||
| "node:stream": [">= 14.18 && < 15", ">= 16"], | ||
| "stream/consumers": ">= 16.7", | ||
| "node:stream/consumers": ">= 16.7", | ||
| "stream/promises": ">= 15", | ||
| "node:stream/promises": ">= 16", | ||
| "stream/web": ">= 16.5", | ||
| "node:stream/web": ">= 16.5", | ||
| "string_decoder": true, | ||
| "node:string_decoder": [">= 14.18 && < 15", ">= 16"], | ||
| "sys": [">= 0.4 && < 0.7", ">= 0.8"], | ||
| "node:sys": [">= 14.18 && < 15", ">= 16"], | ||
| "test/reporters": ">= 19.9 && < 20.2", | ||
| "node:test/reporters": [ | ||
| ">= 18.17 && < 19", | ||
| ">= 19.9", | ||
| ">= 20" | ||
| ], | ||
| "test/mock_loader": ">= 22.3 && < 22.7", | ||
| "node:test/mock_loader": ">= 22.3 && < 22.7", | ||
| "node:test": [">= 16.17 && < 17", ">= 18"], | ||
| "timers": true, | ||
| "node:timers": [">= 14.18 && < 15", ">= 16"], | ||
| "timers/promises": ">= 15", | ||
| "node:timers/promises": ">= 16", | ||
| "_tls_common": ">= 0.11.13", | ||
| "node:_tls_common": [">= 14.18 && < 15", ">= 16"], | ||
| "_tls_legacy": ">= 0.11.3 && < 10", | ||
| "_tls_wrap": ">= 0.11.3", | ||
| "node:_tls_wrap": [">= 14.18 && < 15", ">= 16"], | ||
| "tls": true, | ||
| "node:tls": [">= 14.18 && < 15", ">= 16"], | ||
| "trace_events": ">= 10", | ||
| "node:trace_events": [">= 14.18 && < 15", ">= 16"], | ||
| "tty": true, | ||
| "node:tty": [">= 14.18 && < 15", ">= 16"], | ||
| "url": true, | ||
| "node:url": [">= 14.18 && < 15", ">= 16"], | ||
| "util": true, | ||
| "node:util": [">= 14.18 && < 15", ">= 16"], | ||
| "util/types": ">= 15.3", | ||
| "node:util/types": ">= 16", | ||
| "v8/tools/arguments": ">= 10 && < 12", | ||
| "v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"], | ||
| "v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"], | ||
| "v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"], | ||
| "v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"], | ||
| "v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"], | ||
| "v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"], | ||
| "v8": ">= 1", | ||
| "node:v8": [">= 14.18 && < 15", ">= 16"], | ||
| "vm": true, | ||
| "node:vm": [">= 14.18 && < 15", ">= 16"], | ||
| "wasi": [ | ||
| ">= 13.4 && < 13.5", | ||
| ">= 18.17 && < 19", | ||
| ">= 20" | ||
| ], | ||
| "node:wasi": [">= 18.17 && < 19", ">= 20"], | ||
| "worker_threads": ">= 11.7", | ||
| "node:worker_threads": [">= 14.18 && < 15", ">= 16"], | ||
| "zlib": ">= 0.5", | ||
| "node:zlib": [">= 14.18 && < 15", ">= 16"] | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/is-core-module@2.16.1/node_modules/is-core-module/index.js | ||
| var require_is_core_module = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/is-core-module@2.16.1/node_modules/is-core-module/index.js": ((exports, module) => { | ||
| var hasOwn = require_hasown(); | ||
| function specifierIncluded(current, specifier) { | ||
| var nodeParts = current.split("."); | ||
| var parts = specifier.split(" "); | ||
| var op = parts.length > 1 ? parts[0] : "="; | ||
| var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split("."); | ||
| for (var i = 0; i < 3; ++i) { | ||
| var cur = parseInt(nodeParts[i] || 0, 10); | ||
| var ver = parseInt(versionParts[i] || 0, 10); | ||
| if (cur === ver) continue; | ||
| if (op === "<") return cur < ver; | ||
| if (op === ">=") return cur >= ver; | ||
| return false; | ||
| } | ||
| return op === ">="; | ||
| } | ||
| function matchesRange(current, range) { | ||
| var specifiers = range.split(/ ?&& ?/); | ||
| if (specifiers.length === 0) return false; | ||
| for (var i = 0; i < specifiers.length; ++i) if (!specifierIncluded(current, specifiers[i])) return false; | ||
| return true; | ||
| } | ||
| function versionIncluded(nodeVersion, specifierValue) { | ||
| if (typeof specifierValue === "boolean") return specifierValue; | ||
| var current = typeof nodeVersion === "undefined" ? process.versions && process.versions.node : nodeVersion; | ||
| if (typeof current !== "string") throw new TypeError(typeof nodeVersion === "undefined" ? "Unable to determine current node version" : "If provided, a valid node version is required"); | ||
| if (specifierValue && typeof specifierValue === "object") { | ||
| for (var i = 0; i < specifierValue.length; ++i) if (matchesRange(current, specifierValue[i])) return true; | ||
| return false; | ||
| } | ||
| return matchesRange(current, specifierValue); | ||
| } | ||
| var data = require_core(); | ||
| module.exports = function isCore(x, nodeVersion) { | ||
| return hasOwn(data, x) && versionIncluded(nodeVersion, data[x]); | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| export { require_is_core_module as t }; |
| import { t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| //#region node_modules/.pnpm/is-module@1.0.0/node_modules/is-module/index.js | ||
| var require_is_module = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/is-module@1.0.0/node_modules/is-module/index.js": ((exports, module) => { | ||
| var ES6ImportExportRegExp = /(?:^\s*|[}{\(\);,\n]\s*)(import\s+['"]|(import|module)\s+[^"'\(\)\n;]+\s+from\s+['"]|export\s+(\*|\{|default|function|var|const|let|[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))/; | ||
| var ES6AliasRegExp = /(?:^\s*|[}{\(\);,\n]\s*)(export\s*\*\s*from\s*(?:'([^']+)'|"([^"]+)"))/; | ||
| module.exports = function(sauce) { | ||
| return ES6ImportExportRegExp.test(sauce) || ES6AliasRegExp.test(sauce); | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| export { require_is_module as t }; |
| import { t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| //#region node_modules/.pnpm/is-reference@1.2.1/node_modules/is-reference/dist/is-reference.js | ||
| var require_is_reference = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/is-reference@1.2.1/node_modules/is-reference/dist/is-reference.js": ((exports, module) => { | ||
| (function(global, factory) { | ||
| typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = global || self, global.isReference = factory()); | ||
| })(exports, (function() { | ||
| function isReference(node, parent) { | ||
| if (node.type === "MemberExpression") return !node.computed && isReference(node.object, node); | ||
| if (node.type === "Identifier") { | ||
| if (!parent) return true; | ||
| switch (parent.type) { | ||
| case "MemberExpression": return parent.computed || node === parent.object; | ||
| case "MethodDefinition": return parent.computed; | ||
| case "FieldDefinition": return parent.computed || node === parent.value; | ||
| case "Property": return parent.computed || node === parent.value; | ||
| case "ExportSpecifier": | ||
| case "ImportSpecifier": return node === parent.local; | ||
| case "LabeledStatement": | ||
| case "BreakStatement": | ||
| case "ContinueStatement": return false; | ||
| default: return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
| return isReference; | ||
| })); | ||
| }) }); | ||
| //#endregion | ||
| export { require_is_reference as t }; |
| import { t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| //#region node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.js | ||
| var require_js_tokens = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.js": ((exports, module) => { | ||
| var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]?|[^\/[\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/uy, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace; | ||
| Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y; | ||
| Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/uy; | ||
| StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y; | ||
| NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y; | ||
| Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y; | ||
| WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/uy; | ||
| LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y; | ||
| MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y; | ||
| SingleLineComment = /\/\/.*/y; | ||
| HashbangComment = /^#!.*/; | ||
| JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y; | ||
| JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/uy; | ||
| JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y; | ||
| JSXText = /[^<>{}]+/y; | ||
| TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/; | ||
| TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/; | ||
| KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/; | ||
| KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/; | ||
| Newline = RegExp(LineTerminatorSequence.source); | ||
| module.exports = function* (input, { jsx = false } = {}) { | ||
| var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack; | ||
| ({length} = input); | ||
| lastIndex = 0; | ||
| lastSignificantToken = ""; | ||
| stack = [{ tag: "JS" }]; | ||
| braces = []; | ||
| parenNesting = 0; | ||
| postfixIncDec = false; | ||
| if (match = HashbangComment.exec(input)) { | ||
| yield { | ||
| type: "HashbangComment", | ||
| value: match[0] | ||
| }; | ||
| lastIndex = match[0].length; | ||
| } | ||
| while (lastIndex < length) { | ||
| mode = stack[stack.length - 1]; | ||
| switch (mode.tag) { | ||
| case "JS": | ||
| case "JSNonExpressionParen": | ||
| case "InterpolationInTemplate": | ||
| case "InterpolationInJSX": | ||
| if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { | ||
| RegularExpressionLiteral.lastIndex = lastIndex; | ||
| if (match = RegularExpressionLiteral.exec(input)) { | ||
| lastIndex = RegularExpressionLiteral.lastIndex; | ||
| lastSignificantToken = match[0]; | ||
| postfixIncDec = true; | ||
| yield { | ||
| type: "RegularExpressionLiteral", | ||
| value: match[0], | ||
| closed: match[1] !== void 0 && match[1] !== "\\" | ||
| }; | ||
| continue; | ||
| } | ||
| } | ||
| Punctuator.lastIndex = lastIndex; | ||
| if (match = Punctuator.exec(input)) { | ||
| punctuator = match[0]; | ||
| nextLastIndex = Punctuator.lastIndex; | ||
| nextLastSignificantToken = punctuator; | ||
| switch (punctuator) { | ||
| case "(": | ||
| if (lastSignificantToken === "?NonExpressionParenKeyword") stack.push({ | ||
| tag: "JSNonExpressionParen", | ||
| nesting: parenNesting | ||
| }); | ||
| parenNesting++; | ||
| postfixIncDec = false; | ||
| break; | ||
| case ")": | ||
| parenNesting--; | ||
| postfixIncDec = true; | ||
| if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) { | ||
| stack.pop(); | ||
| nextLastSignificantToken = "?NonExpressionParenEnd"; | ||
| postfixIncDec = false; | ||
| } | ||
| break; | ||
| case "{": | ||
| Punctuator.lastIndex = 0; | ||
| isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken)); | ||
| braces.push(isExpression); | ||
| postfixIncDec = false; | ||
| break; | ||
| case "}": | ||
| switch (mode.tag) { | ||
| case "InterpolationInTemplate": | ||
| if (braces.length === mode.nesting) { | ||
| Template.lastIndex = lastIndex; | ||
| match = Template.exec(input); | ||
| lastIndex = Template.lastIndex; | ||
| lastSignificantToken = match[0]; | ||
| if (match[1] === "${") { | ||
| lastSignificantToken = "?InterpolationInTemplate"; | ||
| postfixIncDec = false; | ||
| yield { | ||
| type: "TemplateMiddle", | ||
| value: match[0] | ||
| }; | ||
| } else { | ||
| stack.pop(); | ||
| postfixIncDec = true; | ||
| yield { | ||
| type: "TemplateTail", | ||
| value: match[0], | ||
| closed: match[1] === "`" | ||
| }; | ||
| } | ||
| continue; | ||
| } | ||
| break; | ||
| case "InterpolationInJSX": if (braces.length === mode.nesting) { | ||
| stack.pop(); | ||
| lastIndex += 1; | ||
| lastSignificantToken = "}"; | ||
| yield { | ||
| type: "JSXPunctuator", | ||
| value: "}" | ||
| }; | ||
| continue; | ||
| } | ||
| } | ||
| postfixIncDec = braces.pop(); | ||
| nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}"; | ||
| break; | ||
| case "]": | ||
| postfixIncDec = true; | ||
| break; | ||
| case "++": | ||
| case "--": | ||
| nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec"; | ||
| break; | ||
| case "<": | ||
| if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { | ||
| stack.push({ tag: "JSXTag" }); | ||
| lastIndex += 1; | ||
| lastSignificantToken = "<"; | ||
| yield { | ||
| type: "JSXPunctuator", | ||
| value: punctuator | ||
| }; | ||
| continue; | ||
| } | ||
| postfixIncDec = false; | ||
| break; | ||
| default: postfixIncDec = false; | ||
| } | ||
| lastIndex = nextLastIndex; | ||
| lastSignificantToken = nextLastSignificantToken; | ||
| yield { | ||
| type: "Punctuator", | ||
| value: punctuator | ||
| }; | ||
| continue; | ||
| } | ||
| Identifier.lastIndex = lastIndex; | ||
| if (match = Identifier.exec(input)) { | ||
| lastIndex = Identifier.lastIndex; | ||
| nextLastSignificantToken = match[0]; | ||
| switch (match[0]) { | ||
| case "for": | ||
| case "if": | ||
| case "while": | ||
| case "with": if (lastSignificantToken !== "." && lastSignificantToken !== "?.") nextLastSignificantToken = "?NonExpressionParenKeyword"; | ||
| } | ||
| lastSignificantToken = nextLastSignificantToken; | ||
| postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]); | ||
| yield { | ||
| type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName", | ||
| value: match[0] | ||
| }; | ||
| continue; | ||
| } | ||
| StringLiteral.lastIndex = lastIndex; | ||
| if (match = StringLiteral.exec(input)) { | ||
| lastIndex = StringLiteral.lastIndex; | ||
| lastSignificantToken = match[0]; | ||
| postfixIncDec = true; | ||
| yield { | ||
| type: "StringLiteral", | ||
| value: match[0], | ||
| closed: match[2] !== void 0 | ||
| }; | ||
| continue; | ||
| } | ||
| NumericLiteral.lastIndex = lastIndex; | ||
| if (match = NumericLiteral.exec(input)) { | ||
| lastIndex = NumericLiteral.lastIndex; | ||
| lastSignificantToken = match[0]; | ||
| postfixIncDec = true; | ||
| yield { | ||
| type: "NumericLiteral", | ||
| value: match[0] | ||
| }; | ||
| continue; | ||
| } | ||
| Template.lastIndex = lastIndex; | ||
| if (match = Template.exec(input)) { | ||
| lastIndex = Template.lastIndex; | ||
| lastSignificantToken = match[0]; | ||
| if (match[1] === "${") { | ||
| lastSignificantToken = "?InterpolationInTemplate"; | ||
| stack.push({ | ||
| tag: "InterpolationInTemplate", | ||
| nesting: braces.length | ||
| }); | ||
| postfixIncDec = false; | ||
| yield { | ||
| type: "TemplateHead", | ||
| value: match[0] | ||
| }; | ||
| } else { | ||
| postfixIncDec = true; | ||
| yield { | ||
| type: "NoSubstitutionTemplate", | ||
| value: match[0], | ||
| closed: match[1] === "`" | ||
| }; | ||
| } | ||
| continue; | ||
| } | ||
| break; | ||
| case "JSXTag": | ||
| case "JSXTagEnd": | ||
| JSXPunctuator.lastIndex = lastIndex; | ||
| if (match = JSXPunctuator.exec(input)) { | ||
| lastIndex = JSXPunctuator.lastIndex; | ||
| nextLastSignificantToken = match[0]; | ||
| switch (match[0]) { | ||
| case "<": | ||
| stack.push({ tag: "JSXTag" }); | ||
| break; | ||
| case ">": | ||
| stack.pop(); | ||
| if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") { | ||
| nextLastSignificantToken = "?JSX"; | ||
| postfixIncDec = true; | ||
| } else stack.push({ tag: "JSXChildren" }); | ||
| break; | ||
| case "{": | ||
| stack.push({ | ||
| tag: "InterpolationInJSX", | ||
| nesting: braces.length | ||
| }); | ||
| nextLastSignificantToken = "?InterpolationInJSX"; | ||
| postfixIncDec = false; | ||
| break; | ||
| case "/": if (lastSignificantToken === "<") { | ||
| stack.pop(); | ||
| if (stack[stack.length - 1].tag === "JSXChildren") stack.pop(); | ||
| stack.push({ tag: "JSXTagEnd" }); | ||
| } | ||
| } | ||
| lastSignificantToken = nextLastSignificantToken; | ||
| yield { | ||
| type: "JSXPunctuator", | ||
| value: match[0] | ||
| }; | ||
| continue; | ||
| } | ||
| JSXIdentifier.lastIndex = lastIndex; | ||
| if (match = JSXIdentifier.exec(input)) { | ||
| lastIndex = JSXIdentifier.lastIndex; | ||
| lastSignificantToken = match[0]; | ||
| yield { | ||
| type: "JSXIdentifier", | ||
| value: match[0] | ||
| }; | ||
| continue; | ||
| } | ||
| JSXString.lastIndex = lastIndex; | ||
| if (match = JSXString.exec(input)) { | ||
| lastIndex = JSXString.lastIndex; | ||
| lastSignificantToken = match[0]; | ||
| yield { | ||
| type: "JSXString", | ||
| value: match[0], | ||
| closed: match[2] !== void 0 | ||
| }; | ||
| continue; | ||
| } | ||
| break; | ||
| case "JSXChildren": | ||
| JSXText.lastIndex = lastIndex; | ||
| if (match = JSXText.exec(input)) { | ||
| lastIndex = JSXText.lastIndex; | ||
| lastSignificantToken = match[0]; | ||
| yield { | ||
| type: "JSXText", | ||
| value: match[0] | ||
| }; | ||
| continue; | ||
| } | ||
| switch (input[lastIndex]) { | ||
| case "<": | ||
| stack.push({ tag: "JSXTag" }); | ||
| lastIndex++; | ||
| lastSignificantToken = "<"; | ||
| yield { | ||
| type: "JSXPunctuator", | ||
| value: "<" | ||
| }; | ||
| continue; | ||
| case "{": | ||
| stack.push({ | ||
| tag: "InterpolationInJSX", | ||
| nesting: braces.length | ||
| }); | ||
| lastIndex++; | ||
| lastSignificantToken = "?InterpolationInJSX"; | ||
| postfixIncDec = false; | ||
| yield { | ||
| type: "JSXPunctuator", | ||
| value: "{" | ||
| }; | ||
| continue; | ||
| } | ||
| } | ||
| WhiteSpace.lastIndex = lastIndex; | ||
| if (match = WhiteSpace.exec(input)) { | ||
| lastIndex = WhiteSpace.lastIndex; | ||
| yield { | ||
| type: "WhiteSpace", | ||
| value: match[0] | ||
| }; | ||
| continue; | ||
| } | ||
| LineTerminatorSequence.lastIndex = lastIndex; | ||
| if (match = LineTerminatorSequence.exec(input)) { | ||
| lastIndex = LineTerminatorSequence.lastIndex; | ||
| postfixIncDec = false; | ||
| if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere"; | ||
| yield { | ||
| type: "LineTerminatorSequence", | ||
| value: match[0] | ||
| }; | ||
| continue; | ||
| } | ||
| MultiLineComment.lastIndex = lastIndex; | ||
| if (match = MultiLineComment.exec(input)) { | ||
| lastIndex = MultiLineComment.lastIndex; | ||
| if (Newline.test(match[0])) { | ||
| postfixIncDec = false; | ||
| if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere"; | ||
| } | ||
| yield { | ||
| type: "MultiLineComment", | ||
| value: match[0], | ||
| closed: match[1] !== void 0 | ||
| }; | ||
| continue; | ||
| } | ||
| SingleLineComment.lastIndex = lastIndex; | ||
| if (match = SingleLineComment.exec(input)) { | ||
| lastIndex = SingleLineComment.lastIndex; | ||
| postfixIncDec = false; | ||
| yield { | ||
| type: "SingleLineComment", | ||
| value: match[0] | ||
| }; | ||
| continue; | ||
| } | ||
| firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex)); | ||
| lastIndex += firstCodePoint.length; | ||
| lastSignificantToken = firstCodePoint; | ||
| postfixIncDec = false; | ||
| yield { | ||
| type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid", | ||
| value: firstCodePoint | ||
| }; | ||
| } | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| export { require_js_tokens as t }; |
| //#region node_modules/.pnpm/knitwork@1.2.0/node_modules/knitwork/dist/index.mjs | ||
| function genString(input, options = {}) { | ||
| const str = JSON.stringify(input); | ||
| if (!options.singleQuotes) return str; | ||
| return `'${escapeString(str).slice(1, -1)}'`; | ||
| } | ||
| const NEEDS_ESCAPE_RE = /[\n\r'\\\u2028\u2029]/; | ||
| const QUOTE_NEWLINE_RE = /([\n\r'\u2028\u2029])/g; | ||
| const BACKSLASH_RE = /\\/g; | ||
| function escapeString(id) { | ||
| if (!NEEDS_ESCAPE_RE.test(id)) return id; | ||
| return id.replace(BACKSLASH_RE, "\\\\").replace(QUOTE_NEWLINE_RE, "\\$1"); | ||
| } | ||
| function genSafeVariableName(name) { | ||
| if (reservedNames.has(name)) return `_${name}`; | ||
| return name.replace(/^\d/, (r) => `_${r}`).replace(/\W/g, (r) => "_" + r.charCodeAt(0)); | ||
| } | ||
| const reservedNames = /* @__PURE__ */ new Set([ | ||
| "Infinity", | ||
| "NaN", | ||
| "arguments", | ||
| "await", | ||
| "break", | ||
| "case", | ||
| "catch", | ||
| "class", | ||
| "const", | ||
| "continue", | ||
| "debugger", | ||
| "default", | ||
| "delete", | ||
| "do", | ||
| "else", | ||
| "enum", | ||
| "eval", | ||
| "export", | ||
| "extends", | ||
| "false", | ||
| "finally", | ||
| "for", | ||
| "function", | ||
| "if", | ||
| "implements", | ||
| "import", | ||
| "in", | ||
| "instanceof", | ||
| "interface", | ||
| "let", | ||
| "new", | ||
| "null", | ||
| "package", | ||
| "private", | ||
| "protected", | ||
| "public", | ||
| "return", | ||
| "static", | ||
| "super", | ||
| "switch", | ||
| "this", | ||
| "throw", | ||
| "true", | ||
| "try", | ||
| "typeof", | ||
| "undefined", | ||
| "var", | ||
| "void", | ||
| "while", | ||
| "with", | ||
| "yield" | ||
| ]); | ||
| function _genStatement(type, specifier, names, options = {}) { | ||
| const specifierString = genString(specifier, options); | ||
| if (!names) return `${type} ${specifierString};`; | ||
| const nameArray = Array.isArray(names); | ||
| const namesString = (nameArray ? names : [names]).map((index) => { | ||
| if (typeof index === "string") return { name: index }; | ||
| if (index.name === index.as) index = { name: index.name }; | ||
| return index; | ||
| }).map((index) => index.as ? `${index.name} as ${index.as}` : index.name).join(", "); | ||
| if (nameArray) return `${type} { ${namesString} } from ${genString(specifier, options)}${_genImportAttributes(type, options)};`; | ||
| return `${type} ${namesString} from ${genString(specifier, options)}${_genImportAttributes(type, options)};`; | ||
| } | ||
| function _genImportAttributes(type, options) { | ||
| if (type === "import type" || type === "export type") return ""; | ||
| if (typeof options.attributes?.type === "string") return ` with { type: ${genString(options.attributes.type)} }`; | ||
| if (typeof options.assert?.type === "string") return ` assert { type: ${genString(options.assert.type)} }`; | ||
| return ""; | ||
| } | ||
| function genImport(specifier, imports, options = {}) { | ||
| return _genStatement("import", specifier, imports, options); | ||
| } | ||
| function wrapInDelimiters(lines, indent = "", delimiters = "{}", withComma = true) { | ||
| if (lines.length === 0) return delimiters; | ||
| const [start, end] = delimiters; | ||
| return `${start} | ||
| ` + lines.join(withComma ? ",\n" : "\n") + ` | ||
| ${indent}${end}`; | ||
| } | ||
| const VALID_IDENTIFIER_RE = /^[$_]?([A-Z_a-z]\w*|\d)$/; | ||
| function genObjectKey(key) { | ||
| return VALID_IDENTIFIER_RE.test(key) ? key : genString(key); | ||
| } | ||
| function genObjectFromRaw(object, indent = "", options = {}) { | ||
| return genObjectFromRawEntries(Object.entries(object), indent, options); | ||
| } | ||
| function genArrayFromRaw(array, indent = "", options = {}) { | ||
| const newIdent = indent + " "; | ||
| return wrapInDelimiters(array.map((index) => `${newIdent}${genRawValue(index, newIdent, options)}`), indent, "[]"); | ||
| } | ||
| function genObjectFromRawEntries(array, indent = "", options = {}) { | ||
| const newIdent = indent + " "; | ||
| return wrapInDelimiters(array.map(([key, value]) => `${newIdent}${genObjectKey(key)}: ${genRawValue(value, newIdent, options)}`), indent, "{}"); | ||
| } | ||
| function genRawValue(value, indent = "", options = {}) { | ||
| if (value === void 0) return "undefined"; | ||
| if (value === null) return "null"; | ||
| if (Array.isArray(value)) return genArrayFromRaw(value, indent, options); | ||
| if (value && typeof value === "object") return genObjectFromRaw(value, indent, options); | ||
| if (options.preserveTypes && typeof value !== "function") return JSON.stringify(value); | ||
| return value.toString(); | ||
| } | ||
| //#endregion | ||
| export { genString as a, genSafeVariableName as i, genObjectFromRaw as n, genObjectKey as r, genImport as t }; |
| import { C as isAbsolute$1, T as normalize$1, k as resolve$2, w as join$1 } from "./c12.mjs"; | ||
| import { r as tokenizer } from "./acorn.mjs"; | ||
| import { a as h, o as x } from "./confbox.mjs"; | ||
| import { builtinModules, createRequire } from "node:module"; | ||
| import path, { dirname, join, win32 } from "node:path"; | ||
| import process$1 from "node:process"; | ||
| import fs, { promises, realpathSync, statSync } from "node:fs"; | ||
| import { joinURL } from "ufo"; | ||
| import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url"; | ||
| import assert from "node:assert"; | ||
| import v8 from "node:v8"; | ||
| import { format, inspect } from "node:util"; | ||
| import fsp from "node:fs/promises"; | ||
| //#region node_modules/.pnpm/pkg-types@1.3.1/node_modules/pkg-types/dist/index.mjs | ||
| const defaultFindOptions = { | ||
| startingFrom: ".", | ||
| rootPattern: /^node_modules$/, | ||
| reverse: false, | ||
| test: (filePath) => { | ||
| try { | ||
| if (statSync(filePath).isFile()) return true; | ||
| } catch {} | ||
| } | ||
| }; | ||
| async function findFile(filename, _options = {}) { | ||
| const filenames = Array.isArray(filename) ? filename : [filename]; | ||
| const options = { | ||
| ...defaultFindOptions, | ||
| ..._options | ||
| }; | ||
| const basePath = resolve$2(options.startingFrom); | ||
| const leadingSlash = basePath[0] === "/"; | ||
| const segments = basePath.split("/").filter(Boolean); | ||
| if (leadingSlash) segments[0] = "/" + segments[0]; | ||
| let root = segments.findIndex((r) => r.match(options.rootPattern)); | ||
| if (root === -1) root = 0; | ||
| if (options.reverse) for (let index = root + 1; index <= segments.length; index++) for (const filename2 of filenames) { | ||
| const filePath = join$1(...segments.slice(0, index), filename2); | ||
| if (await options.test(filePath)) return filePath; | ||
| } | ||
| else for (let index = segments.length; index > root; index--) for (const filename2 of filenames) { | ||
| const filePath = join$1(...segments.slice(0, index), filename2); | ||
| if (await options.test(filePath)) return filePath; | ||
| } | ||
| throw new Error(`Cannot find matching ${filename} in ${options.startingFrom} or parent directories`); | ||
| } | ||
| function findNearestFile(filename, _options = {}) { | ||
| return findFile(filename, _options); | ||
| } | ||
| const FileCache = /* @__PURE__ */ new Map(); | ||
| async function readPackageJSON(id, options = {}) { | ||
| const resolvedPath = await resolvePackageJSON(id, options); | ||
| const cache$1 = options.cache && typeof options.cache !== "boolean" ? options.cache : FileCache; | ||
| if (options.cache && cache$1.has(resolvedPath)) return cache$1.get(resolvedPath); | ||
| const blob = await promises.readFile(resolvedPath, "utf8"); | ||
| let parsed; | ||
| try { | ||
| parsed = x(blob); | ||
| } catch { | ||
| parsed = h(blob); | ||
| } | ||
| cache$1.set(resolvedPath, parsed); | ||
| return parsed; | ||
| } | ||
| async function resolvePackageJSON(id = process.cwd(), options = {}) { | ||
| return findNearestFile("package.json", { | ||
| startingFrom: isAbsolute$1(id) ? id : await resolvePath(id, options), | ||
| ...options | ||
| }); | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/mlly@1.8.0/node_modules/mlly/dist/index.mjs | ||
| const BUILTIN_MODULES = new Set(builtinModules); | ||
| function normalizeSlash(path$1) { | ||
| return path$1.replace(/\\/g, "/"); | ||
| } | ||
| function matchAll(regex, string, addition) { | ||
| const matches = []; | ||
| for (const match of string.matchAll(regex)) matches.push({ | ||
| ...addition, | ||
| ...match.groups, | ||
| code: match[0], | ||
| start: match.index, | ||
| end: (match.index || 0) + match[0].length | ||
| }); | ||
| return matches; | ||
| } | ||
| function clearImports(imports) { | ||
| return (imports || "").replace(/\/\/[^\n]*\n|\/\*.*\*\//g, "").replace(/\s+/g, " "); | ||
| } | ||
| function getImportNames(cleanedImports) { | ||
| const topLevelImports = cleanedImports.replace(/{[^}]*}/, ""); | ||
| return { | ||
| namespacedImport: topLevelImports.match(/\* as \s*(\S*)/)?.[1], | ||
| defaultImport: topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0 | ||
| }; | ||
| } | ||
| /** | ||
| * @typedef ErrnoExceptionFields | ||
| * @property {number | undefined} [errnode] | ||
| * @property {string | undefined} [code] | ||
| * @property {string | undefined} [path] | ||
| * @property {string | undefined} [syscall] | ||
| * @property {string | undefined} [url] | ||
| * | ||
| * @typedef {Error & ErrnoExceptionFields} ErrnoException | ||
| */ | ||
| const own$1 = {}.hasOwnProperty; | ||
| const classRegExp = /^([A-Z][a-z\d]*)+$/; | ||
| const kTypes = new Set([ | ||
| "string", | ||
| "function", | ||
| "number", | ||
| "object", | ||
| "Function", | ||
| "Object", | ||
| "boolean", | ||
| "bigint", | ||
| "symbol" | ||
| ]); | ||
| const codes = {}; | ||
| /** | ||
| * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'. | ||
| * We cannot use Intl.ListFormat because it's not available in | ||
| * --without-intl builds. | ||
| * | ||
| * @param {Array<string>} array | ||
| * An array of strings. | ||
| * @param {string} [type] | ||
| * The list type to be inserted before the last element. | ||
| * @returns {string} | ||
| */ | ||
| function formatList(array, type = "and") { | ||
| return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array[array.length - 1]}`; | ||
| } | ||
| /** @type {Map<string, MessageFunction | string>} */ | ||
| const messages = /* @__PURE__ */ new Map(); | ||
| const nodeInternalPrefix = "__node_internal_"; | ||
| /** @type {number} */ | ||
| let userStackTraceLimit; | ||
| codes.ERR_INVALID_ARG_TYPE = createError( | ||
| "ERR_INVALID_ARG_TYPE", | ||
| /** | ||
| * @param {string} name | ||
| * @param {Array<string> | string} expected | ||
| * @param {unknown} actual | ||
| */ | ||
| (name, expected, actual) => { | ||
| assert(typeof name === "string", "'name' must be a string"); | ||
| if (!Array.isArray(expected)) expected = [expected]; | ||
| let message = "The "; | ||
| if (name.endsWith(" argument")) message += `${name} `; | ||
| else { | ||
| const type = name.includes(".") ? "property" : "argument"; | ||
| message += `"${name}" ${type} `; | ||
| } | ||
| message += "must be "; | ||
| /** @type {Array<string>} */ | ||
| const types = []; | ||
| /** @type {Array<string>} */ | ||
| const instances = []; | ||
| /** @type {Array<string>} */ | ||
| const other = []; | ||
| for (const value of expected) { | ||
| assert(typeof value === "string", "All expected entries have to be of type string"); | ||
| if (kTypes.has(value)) types.push(value.toLowerCase()); | ||
| else if (classRegExp.exec(value) === null) { | ||
| assert(value !== "object", "The value \"object\" should be written as \"Object\""); | ||
| other.push(value); | ||
| } else instances.push(value); | ||
| } | ||
| if (instances.length > 0) { | ||
| const pos = types.indexOf("object"); | ||
| if (pos !== -1) { | ||
| types.slice(pos, 1); | ||
| instances.push("Object"); | ||
| } | ||
| } | ||
| if (types.length > 0) { | ||
| message += `${types.length > 1 ? "one of type" : "of type"} ${formatList(types, "or")}`; | ||
| if (instances.length > 0 || other.length > 0) message += " or "; | ||
| } | ||
| if (instances.length > 0) { | ||
| message += `an instance of ${formatList(instances, "or")}`; | ||
| if (other.length > 0) message += " or "; | ||
| } | ||
| if (other.length > 0) if (other.length > 1) message += `one of ${formatList(other, "or")}`; | ||
| else { | ||
| if (other[0].toLowerCase() !== other[0]) message += "an "; | ||
| message += `${other[0]}`; | ||
| } | ||
| message += `. Received ${determineSpecificType(actual)}`; | ||
| return message; | ||
| }, | ||
| TypeError | ||
| ); | ||
| codes.ERR_INVALID_MODULE_SPECIFIER = createError( | ||
| "ERR_INVALID_MODULE_SPECIFIER", | ||
| /** | ||
| * @param {string} request | ||
| * @param {string} reason | ||
| * @param {string} [base] | ||
| */ | ||
| (request, reason, base = void 0) => { | ||
| return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`; | ||
| }, | ||
| TypeError | ||
| ); | ||
| codes.ERR_INVALID_PACKAGE_CONFIG = createError( | ||
| "ERR_INVALID_PACKAGE_CONFIG", | ||
| /** | ||
| * @param {string} path | ||
| * @param {string} [base] | ||
| * @param {string} [message] | ||
| */ | ||
| (path$1, base, message) => { | ||
| return `Invalid package config ${path$1}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`; | ||
| }, | ||
| Error | ||
| ); | ||
| codes.ERR_INVALID_PACKAGE_TARGET = createError( | ||
| "ERR_INVALID_PACKAGE_TARGET", | ||
| /** | ||
| * @param {string} packagePath | ||
| * @param {string} key | ||
| * @param {unknown} target | ||
| * @param {boolean} [isImport=false] | ||
| * @param {string} [base] | ||
| */ | ||
| (packagePath, key, target, isImport = false, base = void 0) => { | ||
| const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./"); | ||
| if (key === ".") { | ||
| assert(isImport === false); | ||
| return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`; | ||
| } | ||
| return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`; | ||
| }, | ||
| Error | ||
| ); | ||
| codes.ERR_MODULE_NOT_FOUND = createError( | ||
| "ERR_MODULE_NOT_FOUND", | ||
| /** | ||
| * @param {string} path | ||
| * @param {string} base | ||
| * @param {boolean} [exactUrl] | ||
| */ | ||
| (path$1, base, exactUrl = false) => { | ||
| return `Cannot find ${exactUrl ? "module" : "package"} '${path$1}' imported from ${base}`; | ||
| }, | ||
| Error | ||
| ); | ||
| codes.ERR_NETWORK_IMPORT_DISALLOWED = createError("ERR_NETWORK_IMPORT_DISALLOWED", "import of '%s' by %s is not supported: %s", Error); | ||
| codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError( | ||
| "ERR_PACKAGE_IMPORT_NOT_DEFINED", | ||
| /** | ||
| * @param {string} specifier | ||
| * @param {string} packagePath | ||
| * @param {string} base | ||
| */ | ||
| (specifier, packagePath, base) => { | ||
| return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`; | ||
| }, | ||
| TypeError | ||
| ); | ||
| codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError( | ||
| "ERR_PACKAGE_PATH_NOT_EXPORTED", | ||
| /** | ||
| * @param {string} packagePath | ||
| * @param {string} subpath | ||
| * @param {string} [base] | ||
| */ | ||
| (packagePath, subpath, base = void 0) => { | ||
| if (subpath === ".") return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`; | ||
| return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`; | ||
| }, | ||
| Error | ||
| ); | ||
| codes.ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error); | ||
| codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError("ERR_UNSUPPORTED_RESOLVE_REQUEST", "Failed to resolve module specifier \"%s\" from \"%s\": Invalid relative URL or base scheme is not hierarchical.", TypeError); | ||
| codes.ERR_UNKNOWN_FILE_EXTENSION = createError( | ||
| "ERR_UNKNOWN_FILE_EXTENSION", | ||
| /** | ||
| * @param {string} extension | ||
| * @param {string} path | ||
| */ | ||
| (extension, path$1) => { | ||
| return `Unknown file extension "${extension}" for ${path$1}`; | ||
| }, | ||
| TypeError | ||
| ); | ||
| codes.ERR_INVALID_ARG_VALUE = createError( | ||
| "ERR_INVALID_ARG_VALUE", | ||
| /** | ||
| * @param {string} name | ||
| * @param {unknown} value | ||
| * @param {string} [reason='is invalid'] | ||
| */ | ||
| (name, value, reason = "is invalid") => { | ||
| let inspected = inspect(value); | ||
| if (inspected.length > 128) inspected = `${inspected.slice(0, 128)}...`; | ||
| return `The ${name.includes(".") ? "property" : "argument"} '${name}' ${reason}. Received ${inspected}`; | ||
| }, | ||
| TypeError | ||
| ); | ||
| /** | ||
| * Utility function for registering the error codes. Only used here. Exported | ||
| * *only* to allow for testing. | ||
| * @param {string} sym | ||
| * @param {MessageFunction | string} value | ||
| * @param {ErrorConstructor} constructor | ||
| * @returns {new (...parameters: Array<any>) => Error} | ||
| */ | ||
| function createError(sym, value, constructor) { | ||
| messages.set(sym, value); | ||
| return makeNodeErrorWithCode(constructor, sym); | ||
| } | ||
| /** | ||
| * @param {ErrorConstructor} Base | ||
| * @param {string} key | ||
| * @returns {ErrorConstructor} | ||
| */ | ||
| function makeNodeErrorWithCode(Base, key) { | ||
| return NodeError; | ||
| /** | ||
| * @param {Array<unknown>} parameters | ||
| */ | ||
| function NodeError(...parameters) { | ||
| const limit = Error.stackTraceLimit; | ||
| if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0; | ||
| const error = new Base(); | ||
| if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit; | ||
| const message = getMessage(key, parameters, error); | ||
| Object.defineProperties(error, { | ||
| message: { | ||
| value: message, | ||
| enumerable: false, | ||
| writable: true, | ||
| configurable: true | ||
| }, | ||
| toString: { | ||
| value() { | ||
| return `${this.name} [${key}]: ${this.message}`; | ||
| }, | ||
| enumerable: false, | ||
| writable: true, | ||
| configurable: true | ||
| } | ||
| }); | ||
| captureLargerStackTrace(error); | ||
| error.code = key; | ||
| return error; | ||
| } | ||
| } | ||
| /** | ||
| * @returns {boolean} | ||
| */ | ||
| function isErrorStackTraceLimitWritable() { | ||
| try { | ||
| if (v8.startupSnapshot.isBuildingSnapshot()) return false; | ||
| } catch {} | ||
| const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); | ||
| if (desc === void 0) return Object.isExtensible(Error); | ||
| return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0; | ||
| } | ||
| /** | ||
| * This function removes unnecessary frames from Node.js core errors. | ||
| * @template {(...parameters: unknown[]) => unknown} T | ||
| * @param {T} wrappedFunction | ||
| * @returns {T} | ||
| */ | ||
| function hideStackFrames(wrappedFunction) { | ||
| const hidden = nodeInternalPrefix + wrappedFunction.name; | ||
| Object.defineProperty(wrappedFunction, "name", { value: hidden }); | ||
| return wrappedFunction; | ||
| } | ||
| const captureLargerStackTrace = hideStackFrames( | ||
| /** | ||
| * @param {Error} error | ||
| * @returns {Error} | ||
| */ | ||
| function(error) { | ||
| const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable(); | ||
| if (stackTraceLimitIsWritable) { | ||
| userStackTraceLimit = Error.stackTraceLimit; | ||
| Error.stackTraceLimit = Number.POSITIVE_INFINITY; | ||
| } | ||
| Error.captureStackTrace(error); | ||
| if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit; | ||
| return error; | ||
| } | ||
| ); | ||
| /** | ||
| * @param {string} key | ||
| * @param {Array<unknown>} parameters | ||
| * @param {Error} self | ||
| * @returns {string} | ||
| */ | ||
| function getMessage(key, parameters, self) { | ||
| const message = messages.get(key); | ||
| assert(message !== void 0, "expected `message` to be found"); | ||
| if (typeof message === "function") { | ||
| assert(message.length <= parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`); | ||
| return Reflect.apply(message, self, parameters); | ||
| } | ||
| const regex = /%[dfijoOs]/g; | ||
| let expectedLength = 0; | ||
| while (regex.exec(message) !== null) expectedLength++; | ||
| assert(expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`); | ||
| if (parameters.length === 0) return message; | ||
| parameters.unshift(message); | ||
| return Reflect.apply(format, null, parameters); | ||
| } | ||
| /** | ||
| * Determine the specific type of a value for type-mismatch errors. | ||
| * @param {unknown} value | ||
| * @returns {string} | ||
| */ | ||
| function determineSpecificType(value) { | ||
| if (value === null || value === void 0) return String(value); | ||
| if (typeof value === "function" && value.name) return `function ${value.name}`; | ||
| if (typeof value === "object") { | ||
| if (value.constructor && value.constructor.name) return `an instance of ${value.constructor.name}`; | ||
| return `${inspect(value, { depth: -1 })}`; | ||
| } | ||
| let inspected = inspect(value, { colors: false }); | ||
| if (inspected.length > 28) inspected = `${inspected.slice(0, 25)}...`; | ||
| return `type ${typeof value} (${inspected})`; | ||
| } | ||
| const hasOwnProperty$1 = {}.hasOwnProperty; | ||
| const { ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1 } = codes; | ||
| /** @type {Map<string, PackageConfig>} */ | ||
| const cache = /* @__PURE__ */ new Map(); | ||
| /** | ||
| * @param {string} jsonPath | ||
| * @param {{specifier: URL | string, base?: URL}} options | ||
| * @returns {PackageConfig} | ||
| */ | ||
| function read(jsonPath, { base, specifier }) { | ||
| const existing = cache.get(jsonPath); | ||
| if (existing) return existing; | ||
| /** @type {string | undefined} */ | ||
| let string; | ||
| try { | ||
| string = fs.readFileSync(path.toNamespacedPath(jsonPath), "utf8"); | ||
| } catch (error) { | ||
| const exception = error; | ||
| if (exception.code !== "ENOENT") throw exception; | ||
| } | ||
| /** @type {PackageConfig} */ | ||
| const result = { | ||
| exists: false, | ||
| pjsonPath: jsonPath, | ||
| main: void 0, | ||
| name: void 0, | ||
| type: "none", | ||
| exports: void 0, | ||
| imports: void 0 | ||
| }; | ||
| if (string !== void 0) { | ||
| /** @type {Record<string, unknown>} */ | ||
| let parsed; | ||
| try { | ||
| parsed = JSON.parse(string); | ||
| } catch (error_) { | ||
| const cause = error_; | ||
| const error = new ERR_INVALID_PACKAGE_CONFIG$1(jsonPath, (base ? `"${specifier}" from ` : "") + fileURLToPath(base || specifier), cause.message); | ||
| error.cause = cause; | ||
| throw error; | ||
| } | ||
| result.exists = true; | ||
| if (hasOwnProperty$1.call(parsed, "name") && typeof parsed.name === "string") result.name = parsed.name; | ||
| if (hasOwnProperty$1.call(parsed, "main") && typeof parsed.main === "string") result.main = parsed.main; | ||
| if (hasOwnProperty$1.call(parsed, "exports")) result.exports = parsed.exports; | ||
| if (hasOwnProperty$1.call(parsed, "imports")) result.imports = parsed.imports; | ||
| if (hasOwnProperty$1.call(parsed, "type") && (parsed.type === "commonjs" || parsed.type === "module")) result.type = parsed.type; | ||
| } | ||
| cache.set(jsonPath, result); | ||
| return result; | ||
| } | ||
| /** | ||
| * @param {URL | string} resolved | ||
| * @returns {PackageConfig} | ||
| */ | ||
| function getPackageScopeConfig(resolved) { | ||
| let packageJSONUrl = new URL("package.json", resolved); | ||
| while (true) { | ||
| if (packageJSONUrl.pathname.endsWith("node_modules/package.json")) break; | ||
| const packageConfig = read(fileURLToPath(packageJSONUrl), { specifier: resolved }); | ||
| if (packageConfig.exists) return packageConfig; | ||
| const lastPackageJSONUrl = packageJSONUrl; | ||
| packageJSONUrl = new URL("../package.json", packageJSONUrl); | ||
| if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) break; | ||
| } | ||
| return { | ||
| pjsonPath: fileURLToPath(packageJSONUrl), | ||
| exists: false, | ||
| type: "none" | ||
| }; | ||
| } | ||
| /** | ||
| * Returns the package type for a given URL. | ||
| * @param {URL} url - The URL to get the package type for. | ||
| * @returns {PackageType} | ||
| */ | ||
| function getPackageType(url) { | ||
| return getPackageScopeConfig(url).type; | ||
| } | ||
| const { ERR_UNKNOWN_FILE_EXTENSION } = codes; | ||
| const hasOwnProperty = {}.hasOwnProperty; | ||
| /** @type {Record<string, string>} */ | ||
| const extensionFormatMap = { | ||
| __proto__: null, | ||
| ".cjs": "commonjs", | ||
| ".js": "module", | ||
| ".json": "json", | ||
| ".mjs": "module" | ||
| }; | ||
| /** | ||
| * @param {string | null} mime | ||
| * @returns {string | null} | ||
| */ | ||
| function mimeToFormat(mime) { | ||
| if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)) return "module"; | ||
| if (mime === "application/json") return "json"; | ||
| return null; | ||
| } | ||
| /** | ||
| * @callback ProtocolHandler | ||
| * @param {URL} parsed | ||
| * @param {{parentURL: string, source?: Buffer}} context | ||
| * @param {boolean} ignoreErrors | ||
| * @returns {string | null | void} | ||
| */ | ||
| /** | ||
| * @type {Record<string, ProtocolHandler>} | ||
| */ | ||
| const protocolHandlers = { | ||
| __proto__: null, | ||
| "data:": getDataProtocolModuleFormat, | ||
| "file:": getFileProtocolModuleFormat, | ||
| "http:": getHttpProtocolModuleFormat, | ||
| "https:": getHttpProtocolModuleFormat, | ||
| "node:"() { | ||
| return "builtin"; | ||
| } | ||
| }; | ||
| /** | ||
| * @param {URL} parsed | ||
| */ | ||
| function getDataProtocolModuleFormat(parsed) { | ||
| const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(parsed.pathname) || [ | ||
| null, | ||
| null, | ||
| null | ||
| ]; | ||
| return mimeToFormat(mime); | ||
| } | ||
| /** | ||
| * Returns the file extension from a URL. | ||
| * | ||
| * Should give similar result to | ||
| * `require('node:path').extname(require('node:url').fileURLToPath(url))` | ||
| * when used with a `file:` URL. | ||
| * | ||
| * @param {URL} url | ||
| * @returns {string} | ||
| */ | ||
| function extname$2(url) { | ||
| const pathname = url.pathname; | ||
| let index = pathname.length; | ||
| while (index--) { | ||
| const code = pathname.codePointAt(index); | ||
| if (code === 47) return ""; | ||
| if (code === 46) return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index); | ||
| } | ||
| return ""; | ||
| } | ||
| /** | ||
| * @type {ProtocolHandler} | ||
| */ | ||
| function getFileProtocolModuleFormat(url, _context, ignoreErrors) { | ||
| const value = extname$2(url); | ||
| if (value === ".js") { | ||
| const packageType = getPackageType(url); | ||
| if (packageType !== "none") return packageType; | ||
| return "commonjs"; | ||
| } | ||
| if (value === "") { | ||
| const packageType = getPackageType(url); | ||
| if (packageType === "none" || packageType === "commonjs") return "commonjs"; | ||
| return "module"; | ||
| } | ||
| const format$1 = extensionFormatMap[value]; | ||
| if (format$1) return format$1; | ||
| if (ignoreErrors) return; | ||
| throw new ERR_UNKNOWN_FILE_EXTENSION(value, fileURLToPath(url)); | ||
| } | ||
| function getHttpProtocolModuleFormat() {} | ||
| /** | ||
| * @param {URL} url | ||
| * @param {{parentURL: string}} context | ||
| * @returns {string | null} | ||
| */ | ||
| function defaultGetFormatWithoutErrors(url, context) { | ||
| const protocol = url.protocol; | ||
| if (!hasOwnProperty.call(protocolHandlers, protocol)) return null; | ||
| return protocolHandlers[protocol](url, context, true) || null; | ||
| } | ||
| const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace]; | ||
| const { ERR_INVALID_MODULE_SPECIFIER, ERR_INVALID_PACKAGE_CONFIG, ERR_INVALID_PACKAGE_TARGET, ERR_MODULE_NOT_FOUND, ERR_PACKAGE_IMPORT_NOT_DEFINED, ERR_PACKAGE_PATH_NOT_EXPORTED, ERR_UNSUPPORTED_DIR_IMPORT, ERR_UNSUPPORTED_RESOLVE_REQUEST } = codes; | ||
| const own = {}.hasOwnProperty; | ||
| const invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i; | ||
| const deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i; | ||
| const invalidPackageNameRegEx = /^\.|%|\\/; | ||
| const patternRegEx = /\*/g; | ||
| const encodedSeparatorRegEx = /%2f|%5c/i; | ||
| /** @type {Set<string>} */ | ||
| const emittedPackageWarnings = /* @__PURE__ */ new Set(); | ||
| const doubleSlashRegEx = /[/\\]{2}/; | ||
| /** | ||
| * | ||
| * @param {string} target | ||
| * @param {string} request | ||
| * @param {string} match | ||
| * @param {URL} packageJsonUrl | ||
| * @param {boolean} internal | ||
| * @param {URL} base | ||
| * @param {boolean} isTarget | ||
| */ | ||
| function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) { | ||
| if (process$1.noDeprecation) return; | ||
| const pjsonPath = fileURLToPath(packageJsonUrl); | ||
| const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null; | ||
| process$1.emitWarning(`Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath(base)}` : ""}.`, "DeprecationWarning", "DEP0166"); | ||
| } | ||
| /** | ||
| * @param {URL} url | ||
| * @param {URL} packageJsonUrl | ||
| * @param {URL} base | ||
| * @param {string} [main] | ||
| * @returns {void} | ||
| */ | ||
| function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) { | ||
| if (process$1.noDeprecation) return; | ||
| if (defaultGetFormatWithoutErrors(url, { parentURL: base.href }) !== "module") return; | ||
| const urlPath = fileURLToPath(url.href); | ||
| const packagePath = fileURLToPath(new URL$1(".", packageJsonUrl)); | ||
| const basePath = fileURLToPath(base); | ||
| if (!main) process$1.emitWarning(`No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(packagePath.length)}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`, "DeprecationWarning", "DEP0151"); | ||
| else if (path.resolve(packagePath, main) !== urlPath) process$1.emitWarning(`Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(packagePath.length)}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is deprecated for ES modules.`, "DeprecationWarning", "DEP0151"); | ||
| } | ||
| /** | ||
| * @param {string} path | ||
| * @returns {Stats | undefined} | ||
| */ | ||
| function tryStatSync(path$1) { | ||
| try { | ||
| return statSync(path$1); | ||
| } catch {} | ||
| } | ||
| /** | ||
| * Legacy CommonJS main resolution: | ||
| * 1. let M = pkg_url + (json main field) | ||
| * 2. TRY(M, M.js, M.json, M.node) | ||
| * 3. TRY(M/index.js, M/index.json, M/index.node) | ||
| * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node) | ||
| * 5. NOT_FOUND | ||
| * | ||
| * @param {URL} url | ||
| * @returns {boolean} | ||
| */ | ||
| function fileExists(url) { | ||
| const stats = statSync(url, { throwIfNoEntry: false }); | ||
| const isFile = stats ? stats.isFile() : void 0; | ||
| return isFile === null || isFile === void 0 ? false : isFile; | ||
| } | ||
| /** | ||
| * @param {URL} packageJsonUrl | ||
| * @param {PackageConfig} packageConfig | ||
| * @param {URL} base | ||
| * @returns {URL} | ||
| */ | ||
| function legacyMainResolve(packageJsonUrl, packageConfig, base) { | ||
| /** @type {URL | undefined} */ | ||
| let guess; | ||
| if (packageConfig.main !== void 0) { | ||
| guess = new URL$1(packageConfig.main, packageJsonUrl); | ||
| if (fileExists(guess)) return guess; | ||
| const tries$1 = [ | ||
| `./${packageConfig.main}.js`, | ||
| `./${packageConfig.main}.json`, | ||
| `./${packageConfig.main}.node`, | ||
| `./${packageConfig.main}/index.js`, | ||
| `./${packageConfig.main}/index.json`, | ||
| `./${packageConfig.main}/index.node` | ||
| ]; | ||
| let i$1 = -1; | ||
| while (++i$1 < tries$1.length) { | ||
| guess = new URL$1(tries$1[i$1], packageJsonUrl); | ||
| if (fileExists(guess)) break; | ||
| guess = void 0; | ||
| } | ||
| if (guess) { | ||
| emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); | ||
| return guess; | ||
| } | ||
| } | ||
| const tries = [ | ||
| "./index.js", | ||
| "./index.json", | ||
| "./index.node" | ||
| ]; | ||
| let i = -1; | ||
| while (++i < tries.length) { | ||
| guess = new URL$1(tries[i], packageJsonUrl); | ||
| if (fileExists(guess)) break; | ||
| guess = void 0; | ||
| } | ||
| if (guess) { | ||
| emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); | ||
| return guess; | ||
| } | ||
| throw new ERR_MODULE_NOT_FOUND(fileURLToPath(new URL$1(".", packageJsonUrl)), fileURLToPath(base)); | ||
| } | ||
| /** | ||
| * @param {URL} resolved | ||
| * @param {URL} base | ||
| * @param {boolean} [preserveSymlinks] | ||
| * @returns {URL} | ||
| */ | ||
| function finalizeResolution(resolved, base, preserveSymlinks) { | ||
| if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) throw new ERR_INVALID_MODULE_SPECIFIER(resolved.pathname, "must not include encoded \"/\" or \"\\\" characters", fileURLToPath(base)); | ||
| /** @type {string} */ | ||
| let filePath; | ||
| try { | ||
| filePath = fileURLToPath(resolved); | ||
| } catch (error) { | ||
| const cause = error; | ||
| Object.defineProperty(cause, "input", { value: String(resolved) }); | ||
| Object.defineProperty(cause, "module", { value: String(base) }); | ||
| throw cause; | ||
| } | ||
| const stats = tryStatSync(filePath.endsWith("/") ? filePath.slice(-1) : filePath); | ||
| if (stats && stats.isDirectory()) { | ||
| const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath(base)); | ||
| error.url = String(resolved); | ||
| throw error; | ||
| } | ||
| if (!stats || !stats.isFile()) { | ||
| const error = new ERR_MODULE_NOT_FOUND(filePath || resolved.pathname, base && fileURLToPath(base), true); | ||
| error.url = String(resolved); | ||
| throw error; | ||
| } | ||
| { | ||
| const real = realpathSync(filePath); | ||
| const { search, hash } = resolved; | ||
| resolved = pathToFileURL(real + (filePath.endsWith(path.sep) ? "/" : "")); | ||
| resolved.search = search; | ||
| resolved.hash = hash; | ||
| } | ||
| return resolved; | ||
| } | ||
| /** | ||
| * @param {string} specifier | ||
| * @param {URL | undefined} packageJsonUrl | ||
| * @param {URL} base | ||
| * @returns {Error} | ||
| */ | ||
| function importNotDefined(specifier, packageJsonUrl, base) { | ||
| return new ERR_PACKAGE_IMPORT_NOT_DEFINED(specifier, packageJsonUrl && fileURLToPath(new URL$1(".", packageJsonUrl)), fileURLToPath(base)); | ||
| } | ||
| /** | ||
| * @param {string} subpath | ||
| * @param {URL} packageJsonUrl | ||
| * @param {URL} base | ||
| * @returns {Error} | ||
| */ | ||
| function exportsNotFound(subpath, packageJsonUrl, base) { | ||
| return new ERR_PACKAGE_PATH_NOT_EXPORTED(fileURLToPath(new URL$1(".", packageJsonUrl)), subpath, base && fileURLToPath(base)); | ||
| } | ||
| /** | ||
| * @param {string} request | ||
| * @param {string} match | ||
| * @param {URL} packageJsonUrl | ||
| * @param {boolean} internal | ||
| * @param {URL} [base] | ||
| * @returns {never} | ||
| */ | ||
| function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) { | ||
| throw new ERR_INVALID_MODULE_SPECIFIER(request, `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath(packageJsonUrl)}`, base && fileURLToPath(base)); | ||
| } | ||
| /** | ||
| * @param {string} subpath | ||
| * @param {unknown} target | ||
| * @param {URL} packageJsonUrl | ||
| * @param {boolean} internal | ||
| * @param {URL} [base] | ||
| * @returns {Error} | ||
| */ | ||
| function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) { | ||
| target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`; | ||
| return new ERR_INVALID_PACKAGE_TARGET(fileURLToPath(new URL$1(".", packageJsonUrl)), subpath, target, internal, base && fileURLToPath(base)); | ||
| } | ||
| /** | ||
| * @param {string} target | ||
| * @param {string} subpath | ||
| * @param {string} match | ||
| * @param {URL} packageJsonUrl | ||
| * @param {URL} base | ||
| * @param {boolean} pattern | ||
| * @param {boolean} internal | ||
| * @param {boolean} isPathMap | ||
| * @param {Set<string> | undefined} conditions | ||
| * @returns {URL} | ||
| */ | ||
| function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) { | ||
| if (subpath !== "" && !pattern && target[target.length - 1] !== "/") throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); | ||
| if (!target.startsWith("./")) { | ||
| if (internal && !target.startsWith("../") && !target.startsWith("/")) { | ||
| let isURL = false; | ||
| try { | ||
| new URL$1(target); | ||
| isURL = true; | ||
| } catch {} | ||
| if (!isURL) return packageResolve(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target + subpath, packageJsonUrl, conditions); | ||
| } | ||
| throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); | ||
| } | ||
| if (invalidSegmentRegEx.exec(target.slice(2)) !== null) if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) { | ||
| if (!isPathMap) { | ||
| const request = pattern ? match.replace("*", () => subpath) : match + subpath; | ||
| emitInvalidSegmentDeprecation(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target, request, match, packageJsonUrl, internal, base, true); | ||
| } | ||
| } else throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); | ||
| const resolved = new URL$1(target, packageJsonUrl); | ||
| const resolvedPath = resolved.pathname; | ||
| const packagePath = new URL$1(".", packageJsonUrl).pathname; | ||
| if (!resolvedPath.startsWith(packagePath)) throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); | ||
| if (subpath === "") return resolved; | ||
| if (invalidSegmentRegEx.exec(subpath) !== null) { | ||
| const request = pattern ? match.replace("*", () => subpath) : match + subpath; | ||
| if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) { | ||
| if (!isPathMap) emitInvalidSegmentDeprecation(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target, request, match, packageJsonUrl, internal, base, false); | ||
| } else throwInvalidSubpath(request, match, packageJsonUrl, internal, base); | ||
| } | ||
| if (pattern) return new URL$1(RegExpPrototypeSymbolReplace.call(patternRegEx, resolved.href, () => subpath)); | ||
| return new URL$1(subpath, resolved); | ||
| } | ||
| /** | ||
| * @param {string} key | ||
| * @returns {boolean} | ||
| */ | ||
| function isArrayIndex(key) { | ||
| const keyNumber = Number(key); | ||
| if (`${keyNumber}` !== key) return false; | ||
| return keyNumber >= 0 && keyNumber < 4294967295; | ||
| } | ||
| /** | ||
| * @param {URL} packageJsonUrl | ||
| * @param {unknown} target | ||
| * @param {string} subpath | ||
| * @param {string} packageSubpath | ||
| * @param {URL} base | ||
| * @param {boolean} pattern | ||
| * @param {boolean} internal | ||
| * @param {boolean} isPathMap | ||
| * @param {Set<string> | undefined} conditions | ||
| * @returns {URL | null} | ||
| */ | ||
| function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) { | ||
| if (typeof target === "string") return resolvePackageTargetString(target, subpath, packageSubpath, packageJsonUrl, base, pattern, internal, isPathMap, conditions); | ||
| if (Array.isArray(target)) { | ||
| /** @type {Array<unknown>} */ | ||
| const targetList = target; | ||
| if (targetList.length === 0) return null; | ||
| /** @type {ErrnoException | null | undefined} */ | ||
| let lastException; | ||
| let i = -1; | ||
| while (++i < targetList.length) { | ||
| const targetItem = targetList[i]; | ||
| /** @type {URL | null} */ | ||
| let resolveResult; | ||
| try { | ||
| resolveResult = resolvePackageTarget(packageJsonUrl, targetItem, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions); | ||
| } catch (error) { | ||
| const exception = error; | ||
| lastException = exception; | ||
| if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue; | ||
| throw error; | ||
| } | ||
| if (resolveResult === void 0) continue; | ||
| if (resolveResult === null) { | ||
| lastException = null; | ||
| continue; | ||
| } | ||
| return resolveResult; | ||
| } | ||
| if (lastException === void 0 || lastException === null) return null; | ||
| throw lastException; | ||
| } | ||
| if (typeof target === "object" && target !== null) { | ||
| const keys = Object.getOwnPropertyNames(target); | ||
| let i = -1; | ||
| while (++i < keys.length) { | ||
| const key = keys[i]; | ||
| if (isArrayIndex(key)) throw new ERR_INVALID_PACKAGE_CONFIG(fileURLToPath(packageJsonUrl), base, "\"exports\" cannot contain numeric property keys."); | ||
| } | ||
| i = -1; | ||
| while (++i < keys.length) { | ||
| const key = keys[i]; | ||
| if (key === "default" || conditions && conditions.has(key)) { | ||
| const conditionalTarget = target[key]; | ||
| const resolveResult = resolvePackageTarget(packageJsonUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions); | ||
| if (resolveResult === void 0) continue; | ||
| return resolveResult; | ||
| } | ||
| } | ||
| return null; | ||
| } | ||
| if (target === null) return null; | ||
| throw invalidPackageTarget(packageSubpath, target, packageJsonUrl, internal, base); | ||
| } | ||
| /** | ||
| * @param {unknown} exports | ||
| * @param {URL} packageJsonUrl | ||
| * @param {URL} base | ||
| * @returns {boolean} | ||
| */ | ||
| function isConditionalExportsMainSugar(exports, packageJsonUrl, base) { | ||
| if (typeof exports === "string" || Array.isArray(exports)) return true; | ||
| if (typeof exports !== "object" || exports === null) return false; | ||
| const keys = Object.getOwnPropertyNames(exports); | ||
| let isConditionalSugar = false; | ||
| let i = 0; | ||
| let keyIndex = -1; | ||
| while (++keyIndex < keys.length) { | ||
| const key = keys[keyIndex]; | ||
| const currentIsConditionalSugar = key === "" || key[0] !== "."; | ||
| if (i++ === 0) isConditionalSugar = currentIsConditionalSugar; | ||
| else if (isConditionalSugar !== currentIsConditionalSugar) throw new ERR_INVALID_PACKAGE_CONFIG(fileURLToPath(packageJsonUrl), base, "\"exports\" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only."); | ||
| } | ||
| return isConditionalSugar; | ||
| } | ||
| /** | ||
| * @param {string} match | ||
| * @param {URL} pjsonUrl | ||
| * @param {URL} base | ||
| */ | ||
| function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) { | ||
| if (process$1.noDeprecation) return; | ||
| const pjsonPath = fileURLToPath(pjsonUrl); | ||
| if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return; | ||
| emittedPackageWarnings.add(pjsonPath + "|" + match); | ||
| process$1.emitWarning(`Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`, "DeprecationWarning", "DEP0155"); | ||
| } | ||
| /** | ||
| * @param {URL} packageJsonUrl | ||
| * @param {string} packageSubpath | ||
| * @param {Record<string, unknown>} packageConfig | ||
| * @param {URL} base | ||
| * @param {Set<string> | undefined} conditions | ||
| * @returns {URL} | ||
| */ | ||
| function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) { | ||
| let exports = packageConfig.exports; | ||
| if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) exports = { ".": exports }; | ||
| if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) { | ||
| const target = exports[packageSubpath]; | ||
| const resolveResult = resolvePackageTarget(packageJsonUrl, target, "", packageSubpath, base, false, false, false, conditions); | ||
| if (resolveResult === null || resolveResult === void 0) throw exportsNotFound(packageSubpath, packageJsonUrl, base); | ||
| return resolveResult; | ||
| } | ||
| let bestMatch = ""; | ||
| let bestMatchSubpath = ""; | ||
| const keys = Object.getOwnPropertyNames(exports); | ||
| let i = -1; | ||
| while (++i < keys.length) { | ||
| const key = keys[i]; | ||
| const patternIndex = key.indexOf("*"); | ||
| if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) { | ||
| if (packageSubpath.endsWith("/")) emitTrailingSlashPatternDeprecation(packageSubpath, packageJsonUrl, base); | ||
| const patternTrailer = key.slice(patternIndex + 1); | ||
| if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) { | ||
| bestMatch = key; | ||
| bestMatchSubpath = packageSubpath.slice(patternIndex, packageSubpath.length - patternTrailer.length); | ||
| } | ||
| } | ||
| } | ||
| if (bestMatch) { | ||
| const target = exports[bestMatch]; | ||
| const resolveResult = resolvePackageTarget(packageJsonUrl, target, bestMatchSubpath, bestMatch, base, true, false, packageSubpath.endsWith("/"), conditions); | ||
| if (resolveResult === null || resolveResult === void 0) throw exportsNotFound(packageSubpath, packageJsonUrl, base); | ||
| return resolveResult; | ||
| } | ||
| throw exportsNotFound(packageSubpath, packageJsonUrl, base); | ||
| } | ||
| /** | ||
| * @param {string} a | ||
| * @param {string} b | ||
| */ | ||
| function patternKeyCompare(a, b) { | ||
| const aPatternIndex = a.indexOf("*"); | ||
| const bPatternIndex = b.indexOf("*"); | ||
| const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; | ||
| const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; | ||
| if (baseLengthA > baseLengthB) return -1; | ||
| if (baseLengthB > baseLengthA) return 1; | ||
| if (aPatternIndex === -1) return 1; | ||
| if (bPatternIndex === -1) return -1; | ||
| if (a.length > b.length) return -1; | ||
| if (b.length > a.length) return 1; | ||
| return 0; | ||
| } | ||
| /** | ||
| * @param {string} name | ||
| * @param {URL} base | ||
| * @param {Set<string>} [conditions] | ||
| * @returns {URL} | ||
| */ | ||
| function packageImportsResolve(name, base, conditions) { | ||
| if (name === "#" || name.startsWith("#/") || name.endsWith("/")) throw new ERR_INVALID_MODULE_SPECIFIER(name, "is not a valid internal imports specifier name", fileURLToPath(base)); | ||
| /** @type {URL | undefined} */ | ||
| let packageJsonUrl; | ||
| const packageConfig = getPackageScopeConfig(base); | ||
| if (packageConfig.exists) { | ||
| packageJsonUrl = pathToFileURL(packageConfig.pjsonPath); | ||
| const imports = packageConfig.imports; | ||
| if (imports) if (own.call(imports, name) && !name.includes("*")) { | ||
| const resolveResult = resolvePackageTarget(packageJsonUrl, imports[name], "", name, base, false, true, false, conditions); | ||
| if (resolveResult !== null && resolveResult !== void 0) return resolveResult; | ||
| } else { | ||
| let bestMatch = ""; | ||
| let bestMatchSubpath = ""; | ||
| const keys = Object.getOwnPropertyNames(imports); | ||
| let i = -1; | ||
| while (++i < keys.length) { | ||
| const key = keys[i]; | ||
| const patternIndex = key.indexOf("*"); | ||
| if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) { | ||
| const patternTrailer = key.slice(patternIndex + 1); | ||
| if (name.length >= key.length && name.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) { | ||
| bestMatch = key; | ||
| bestMatchSubpath = name.slice(patternIndex, name.length - patternTrailer.length); | ||
| } | ||
| } | ||
| } | ||
| if (bestMatch) { | ||
| const target = imports[bestMatch]; | ||
| const resolveResult = resolvePackageTarget(packageJsonUrl, target, bestMatchSubpath, bestMatch, base, true, true, false, conditions); | ||
| if (resolveResult !== null && resolveResult !== void 0) return resolveResult; | ||
| } | ||
| } | ||
| } | ||
| throw importNotDefined(name, packageJsonUrl, base); | ||
| } | ||
| /** | ||
| * @param {string} specifier | ||
| * @param {URL} base | ||
| */ | ||
| function parsePackageName(specifier, base) { | ||
| let separatorIndex = specifier.indexOf("/"); | ||
| let validPackageName = true; | ||
| let isScoped = false; | ||
| if (specifier[0] === "@") { | ||
| isScoped = true; | ||
| if (separatorIndex === -1 || specifier.length === 0) validPackageName = false; | ||
| else separatorIndex = specifier.indexOf("/", separatorIndex + 1); | ||
| } | ||
| const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex); | ||
| if (invalidPackageNameRegEx.exec(packageName) !== null) validPackageName = false; | ||
| if (!validPackageName) throw new ERR_INVALID_MODULE_SPECIFIER(specifier, "is not a valid package name", fileURLToPath(base)); | ||
| return { | ||
| packageName, | ||
| packageSubpath: "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex)), | ||
| isScoped | ||
| }; | ||
| } | ||
| /** | ||
| * @param {string} specifier | ||
| * @param {URL} base | ||
| * @param {Set<string> | undefined} conditions | ||
| * @returns {URL} | ||
| */ | ||
| function packageResolve(specifier, base, conditions) { | ||
| if (builtinModules.includes(specifier)) return new URL$1("node:" + specifier); | ||
| const { packageName, packageSubpath, isScoped } = parsePackageName(specifier, base); | ||
| const packageConfig = getPackageScopeConfig(base); | ||
| /* c8 ignore next 16 */ | ||
| if (packageConfig.exists) { | ||
| const packageJsonUrl$1 = pathToFileURL(packageConfig.pjsonPath); | ||
| if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) return packageExportsResolve(packageJsonUrl$1, packageSubpath, packageConfig, base, conditions); | ||
| } | ||
| let packageJsonUrl = new URL$1("./node_modules/" + packageName + "/package.json", base); | ||
| let packageJsonPath = fileURLToPath(packageJsonUrl); | ||
| /** @type {string} */ | ||
| let lastPath; | ||
| do { | ||
| const stat$1 = tryStatSync(packageJsonPath.slice(0, -13)); | ||
| if (!stat$1 || !stat$1.isDirectory()) { | ||
| lastPath = packageJsonPath; | ||
| packageJsonUrl = new URL$1((isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json", packageJsonUrl); | ||
| packageJsonPath = fileURLToPath(packageJsonUrl); | ||
| continue; | ||
| } | ||
| const packageConfig$1 = read(packageJsonPath, { | ||
| base, | ||
| specifier | ||
| }); | ||
| if (packageConfig$1.exports !== void 0 && packageConfig$1.exports !== null) return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig$1, base, conditions); | ||
| if (packageSubpath === ".") return legacyMainResolve(packageJsonUrl, packageConfig$1, base); | ||
| return new URL$1(packageSubpath, packageJsonUrl); | ||
| } while (packageJsonPath.length !== lastPath.length); | ||
| throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base), false); | ||
| } | ||
| /** | ||
| * @param {string} specifier | ||
| * @returns {boolean} | ||
| */ | ||
| function isRelativeSpecifier(specifier) { | ||
| if (specifier[0] === ".") { | ||
| if (specifier.length === 1 || specifier[1] === "/") return true; | ||
| if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) return true; | ||
| } | ||
| return false; | ||
| } | ||
| /** | ||
| * @param {string} specifier | ||
| * @returns {boolean} | ||
| */ | ||
| function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) { | ||
| if (specifier === "") return false; | ||
| if (specifier[0] === "/") return true; | ||
| return isRelativeSpecifier(specifier); | ||
| } | ||
| /** | ||
| * The “Resolver Algorithm Specification” as detailed in the Node docs (which is | ||
| * sync and slightly lower-level than `resolve`). | ||
| * | ||
| * @param {string} specifier | ||
| * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc. | ||
| * @param {URL} base | ||
| * Full URL (to a file) that `specifier` is resolved relative from. | ||
| * @param {Set<string>} [conditions] | ||
| * Conditions. | ||
| * @param {boolean} [preserveSymlinks] | ||
| * Keep symlinks instead of resolving them. | ||
| * @returns {URL} | ||
| * A URL object to the found thing. | ||
| */ | ||
| function moduleResolve(specifier, base, conditions, preserveSymlinks) { | ||
| const protocol = base.protocol; | ||
| const isRemote = protocol === "data:" || protocol === "http:" || protocol === "https:"; | ||
| /** @type {URL | undefined} */ | ||
| let resolved; | ||
| if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) try { | ||
| resolved = new URL$1(specifier, base); | ||
| } catch (error_) { | ||
| const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base); | ||
| error.cause = error_; | ||
| throw error; | ||
| } | ||
| else if (protocol === "file:" && specifier[0] === "#") resolved = packageImportsResolve(specifier, base, conditions); | ||
| else try { | ||
| resolved = new URL$1(specifier); | ||
| } catch (error_) { | ||
| if (isRemote && !builtinModules.includes(specifier)) { | ||
| const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base); | ||
| error.cause = error_; | ||
| throw error; | ||
| } | ||
| resolved = packageResolve(specifier, base, conditions); | ||
| } | ||
| assert(resolved !== void 0, "expected to be defined"); | ||
| if (resolved.protocol !== "file:") return resolved; | ||
| return finalizeResolution(resolved, base); | ||
| } | ||
| function fileURLToPath$1(id) { | ||
| if (typeof id === "string" && !id.startsWith("file://")) return normalizeSlash(id); | ||
| return normalizeSlash(fileURLToPath(id)); | ||
| } | ||
| function pathToFileURL$1(id) { | ||
| return pathToFileURL(fileURLToPath$1(id)).toString(); | ||
| } | ||
| const INVALID_CHAR_RE = /[\u0000-\u001F"#$&*+,/:;<=>?@[\]^`{|}\u007F]+/g; | ||
| function sanitizeURIComponent(name = "", replacement = "_") { | ||
| return name.replace(INVALID_CHAR_RE, replacement).replace(/%../g, replacement); | ||
| } | ||
| function sanitizeFilePath(filePath = "") { | ||
| return filePath.replace(/\?.*$/, "").split(/[/\\]/g).map((p) => sanitizeURIComponent(p)).join("/").replace(/^([A-Za-z])_\//, "$1:/"); | ||
| } | ||
| function normalizeid(id) { | ||
| if (typeof id !== "string") id = id.toString(); | ||
| if (/(?:node|data|http|https|file):/.test(id)) return id; | ||
| if (BUILTIN_MODULES.has(id)) return "node:" + id; | ||
| return "file://" + encodeURI(normalizeSlash(id)); | ||
| } | ||
| async function loadURL(url) { | ||
| return await promises.readFile(fileURLToPath$1(url), "utf8"); | ||
| } | ||
| const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]); | ||
| const DEFAULT_EXTENSIONS = [ | ||
| ".mjs", | ||
| ".cjs", | ||
| ".js", | ||
| ".json" | ||
| ]; | ||
| const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([ | ||
| "ERR_MODULE_NOT_FOUND", | ||
| "ERR_UNSUPPORTED_DIR_IMPORT", | ||
| "MODULE_NOT_FOUND", | ||
| "ERR_PACKAGE_PATH_NOT_EXPORTED" | ||
| ]); | ||
| function _tryModuleResolve(id, url, conditions) { | ||
| try { | ||
| return moduleResolve(id, url, conditions); | ||
| } catch (error) { | ||
| if (!NOT_FOUND_ERRORS.has(error?.code)) throw error; | ||
| } | ||
| } | ||
| function _resolve$1(id, options = {}) { | ||
| if (typeof id !== "string") if (id instanceof URL) id = fileURLToPath$1(id); | ||
| else throw new TypeError("input must be a `string` or `URL`"); | ||
| if (/(?:node|data|http|https):/.test(id)) return id; | ||
| if (BUILTIN_MODULES.has(id)) return "node:" + id; | ||
| if (id.startsWith("file://")) id = fileURLToPath$1(id); | ||
| if (isAbsolute$1(id)) try { | ||
| if (statSync(id).isFile()) return pathToFileURL$1(id); | ||
| } catch (error) { | ||
| if (error?.code !== "ENOENT") throw error; | ||
| } | ||
| const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET; | ||
| const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString()))); | ||
| if (_urls.length === 0) _urls.push(new URL(pathToFileURL$1(process.cwd()))); | ||
| const urls = [..._urls]; | ||
| for (const url of _urls) if (url.protocol === "file:") urls.push(new URL("./", url), new URL(joinURL(url.pathname, "_index.js"), url), new URL("node_modules", url)); | ||
| let resolved; | ||
| for (const url of urls) { | ||
| resolved = _tryModuleResolve(id, url, conditionsSet); | ||
| if (resolved) break; | ||
| for (const prefix of ["", "/index"]) { | ||
| for (const extension of options.extensions || DEFAULT_EXTENSIONS) { | ||
| resolved = _tryModuleResolve(joinURL(id, prefix) + extension, url, conditionsSet); | ||
| if (resolved) break; | ||
| } | ||
| if (resolved) break; | ||
| } | ||
| if (resolved) break; | ||
| } | ||
| if (!resolved) { | ||
| const error = /* @__PURE__ */ new Error(`Cannot find module ${id} imported from ${urls.join(", ")}`); | ||
| error.code = "ERR_MODULE_NOT_FOUND"; | ||
| throw error; | ||
| } | ||
| return pathToFileURL$1(resolved); | ||
| } | ||
| function resolveSync(id, options) { | ||
| return _resolve$1(id, options); | ||
| } | ||
| function resolve$1(id, options) { | ||
| try { | ||
| return Promise.resolve(resolveSync(id, options)); | ||
| } catch (error) { | ||
| return Promise.reject(error); | ||
| } | ||
| } | ||
| function resolvePathSync(id, options) { | ||
| return fileURLToPath$1(resolveSync(id, options)); | ||
| } | ||
| function resolvePath(id, options) { | ||
| try { | ||
| return Promise.resolve(resolvePathSync(id, options)); | ||
| } catch (error) { | ||
| return Promise.reject(error); | ||
| } | ||
| } | ||
| const NODE_MODULES_RE = /^(.+\/node_modules\/)([^/@]+|@[^/]+\/[^/]+)(\/?.*?)?$/; | ||
| function parseNodeModulePath(path$1) { | ||
| if (!path$1) return {}; | ||
| path$1 = normalize$1(fileURLToPath$1(path$1)); | ||
| const match = NODE_MODULES_RE.exec(path$1); | ||
| if (!match) return {}; | ||
| const [, dir, name, subpath] = match; | ||
| return { | ||
| dir, | ||
| name, | ||
| subpath: subpath ? `.${subpath}` : void 0 | ||
| }; | ||
| } | ||
| async function lookupNodeModuleSubpath(path$1) { | ||
| path$1 = normalize$1(fileURLToPath$1(path$1)); | ||
| const { name, subpath } = parseNodeModulePath(path$1); | ||
| if (!name || !subpath) return subpath; | ||
| const { exports } = await readPackageJSON(path$1).catch(() => {}) || {}; | ||
| if (exports) { | ||
| const resolvedSubpath = _findSubpath(subpath, exports); | ||
| if (resolvedSubpath) return resolvedSubpath; | ||
| } | ||
| return subpath; | ||
| } | ||
| function _findSubpath(subpath, exports) { | ||
| if (typeof exports === "string") exports = { ".": exports }; | ||
| if (!subpath.startsWith(".")) subpath = subpath.startsWith("/") ? `.${subpath}` : `./${subpath}`; | ||
| if (subpath in (exports || {})) return subpath; | ||
| return _flattenExports(exports).find((p) => p.fsPath === subpath)?.subpath; | ||
| } | ||
| function _flattenExports(exports = {}, parentSubpath = "./") { | ||
| return Object.entries(exports).flatMap(([key, value]) => { | ||
| const [subpath, condition] = key.startsWith(".") ? [key.slice(1), void 0] : ["", key]; | ||
| const _subPath = joinURL(parentSubpath, subpath); | ||
| if (typeof value === "string") return [{ | ||
| subpath: _subPath, | ||
| fsPath: value, | ||
| condition | ||
| }]; | ||
| else return _flattenExports(value, _subPath); | ||
| }); | ||
| } | ||
| const ESM_STATIC_IMPORT_RE = /(?<=\s|^|;|\})import\s*(?:[\s"']*(?<imports>[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu; | ||
| const EXPORT_DECAL_RE = /\bexport\s+(?<declaration>(?:async function\s*\*?|function\s*\*?|let|const enum|const|enum|var|class))\s+\*?(?<name>[\w$]+)(?<extraNames>.*,\s*[\s\w:[\]{}]*[\w$\]}]+)*/g; | ||
| const EXPORT_DECAL_TYPE_RE = /\bexport\s+(?<declaration>(?:interface|type|declare (?:async function|function|let|const enum|const|enum|var|class)))\s+(?<name>[\w$]+)/g; | ||
| const EXPORT_NAMED_RE = /\bexport\s*{(?<exports>[^}]+?)[\s,]*}(?:\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g; | ||
| const EXPORT_NAMED_TYPE_RE = /\bexport\s+type\s*{(?<exports>[^}]+?)[\s,]*}(?:\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g; | ||
| const EXPORT_NAMED_DESTRUCT = /\bexport\s+(?:let|var|const)\s+(?:{(?<exports1>[^}]+?)[\s,]*}|\[(?<exports2>[^\]]+?)[\s,]*])\s+=/gm; | ||
| const EXPORT_STAR_RE = /\bexport\s*\*(?:\s*as\s+(?<name>[\w$]+)\s+)?\s*(?:\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g; | ||
| const EXPORT_DEFAULT_RE = /\bexport\s+default\s+(async function|function|class|true|false|\W|\d)|\bexport\s+default\s+(?<defaultName>.*)/g; | ||
| const EXPORT_DEFAULT_CLASS_RE = /\bexport\s+default\s+(?<declaration>class)\s+(?<name>[\w$]+)/g; | ||
| const TYPE_RE = /^\s*?type\s/; | ||
| function findStaticImports(code) { | ||
| return _filterStatement(_tryGetLocations(code, "import"), matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" })); | ||
| } | ||
| function parseStaticImport(matched) { | ||
| const cleanedImports = clearImports(matched.imports); | ||
| const namedImports = {}; | ||
| const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || []; | ||
| for (const namedImport of _matches) { | ||
| const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/); | ||
| const source = _match?.[1] || namedImport.trim(); | ||
| const importName = _match?.[2] || source; | ||
| if (source && !TYPE_RE.test(source)) namedImports[source] = importName; | ||
| } | ||
| const { namespacedImport, defaultImport } = getImportNames(cleanedImports); | ||
| return { | ||
| ...matched, | ||
| defaultImport, | ||
| namespacedImport, | ||
| namedImports | ||
| }; | ||
| } | ||
| function findExports(code) { | ||
| const declaredExports = matchAll(EXPORT_DECAL_RE, code, { type: "declaration" }); | ||
| for (const declaredExport of declaredExports) { | ||
| if (/^export\s+(?:async\s+)?function/.test(declaredExport.code)) continue; | ||
| const extraNamesStr = declaredExport.extraNames; | ||
| if (extraNamesStr) { | ||
| const extraNames = matchAll(/({.*?})|(\[.*?])|(,\s*(?<name>\w+))/g, extraNamesStr, {}).map((m) => m.name).filter(Boolean); | ||
| declaredExport.names = [declaredExport.name, ...extraNames]; | ||
| } | ||
| delete declaredExport.extraNames; | ||
| } | ||
| const namedExports = normalizeNamedExports(matchAll(EXPORT_NAMED_RE, code, { type: "named" })); | ||
| const destructuredExports = matchAll(EXPORT_NAMED_DESTRUCT, code, { type: "named" }); | ||
| for (const namedExport of destructuredExports) { | ||
| namedExport.exports = namedExport.exports1 || namedExport.exports2; | ||
| namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map((name) => name.replace(/^.*?\s*:\s*/, "").replace(/\s*=\s*.*$/, "").trim()); | ||
| } | ||
| const defaultExport = matchAll(EXPORT_DEFAULT_RE, code, { | ||
| type: "default", | ||
| name: "default" | ||
| }); | ||
| const defaultClassExports = matchAll(EXPORT_DEFAULT_CLASS_RE, code, { type: "declaration" }); | ||
| const starExports = matchAll(EXPORT_STAR_RE, code, { type: "star" }); | ||
| const exports = normalizeExports([ | ||
| ...declaredExports, | ||
| ...namedExports, | ||
| ...destructuredExports, | ||
| ...defaultExport, | ||
| ...defaultClassExports, | ||
| ...starExports | ||
| ]); | ||
| if (exports.length === 0) return []; | ||
| const exportLocations = _tryGetLocations(code, "export"); | ||
| if (exportLocations && exportLocations.length === 0) return []; | ||
| return _filterStatement(exportLocations, exports).filter((exp, index, exports2) => { | ||
| const nextExport = exports2[index + 1]; | ||
| return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name; | ||
| }); | ||
| } | ||
| function findTypeExports(code) { | ||
| const declaredExports = matchAll(EXPORT_DECAL_TYPE_RE, code, { type: "declaration" }); | ||
| const namedExports = normalizeNamedExports(matchAll(EXPORT_NAMED_TYPE_RE, code, { type: "named" })); | ||
| const exports = normalizeExports([...declaredExports, ...namedExports]); | ||
| if (exports.length === 0) return []; | ||
| const exportLocations = _tryGetLocations(code, "export"); | ||
| if (exportLocations && exportLocations.length === 0) return []; | ||
| return _filterStatement(exportLocations, exports).filter((exp, index, exports2) => { | ||
| const nextExport = exports2[index + 1]; | ||
| return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name; | ||
| }); | ||
| } | ||
| function normalizeExports(exports) { | ||
| for (const exp of exports) { | ||
| if (!exp.name && exp.names && exp.names.length === 1) exp.name = exp.names[0]; | ||
| if (exp.name === "default" && exp.type !== "default") { | ||
| exp._type = exp.type; | ||
| exp.type = "default"; | ||
| } | ||
| if (!exp.names && exp.name) exp.names = [exp.name]; | ||
| if (exp.type === "declaration" && exp.declaration) exp.declarationType = exp.declaration.replace(/^declare\s*/, ""); | ||
| } | ||
| return exports; | ||
| } | ||
| function normalizeNamedExports(namedExports) { | ||
| for (const namedExport of namedExports) namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map((name) => name.replace(/^.*?\sas\s/, "").trim()); | ||
| return namedExports; | ||
| } | ||
| async function resolveModuleExportNames(id, options) { | ||
| const url = await resolvePath(id, options); | ||
| const exports = findExports(await loadURL(url)); | ||
| const exportNames = new Set(exports.flatMap((exp) => exp.names).filter(Boolean)); | ||
| for (const exp of exports) { | ||
| if (exp.type !== "star" || !exp.specifier) continue; | ||
| const subExports = await resolveModuleExportNames(exp.specifier, { | ||
| ...options, | ||
| url | ||
| }); | ||
| for (const subExport of subExports) exportNames.add(subExport); | ||
| } | ||
| return [...exportNames]; | ||
| } | ||
| function _filterStatement(locations, statements) { | ||
| return statements.filter((exp) => { | ||
| return !locations || locations.some((location) => { | ||
| return exp.start <= location.start && exp.end >= location.end; | ||
| }); | ||
| }); | ||
| } | ||
| function _tryGetLocations(code, label) { | ||
| try { | ||
| return _getLocations(code, label); | ||
| } catch {} | ||
| } | ||
| function _getLocations(code, label) { | ||
| const tokens = tokenizer(code, { | ||
| ecmaVersion: "latest", | ||
| sourceType: "module", | ||
| allowHashBang: true, | ||
| allowAwaitOutsideFunction: true, | ||
| allowImportExportEverywhere: true | ||
| }); | ||
| const locations = []; | ||
| for (const token of tokens) if (token.type.label === label) locations.push({ | ||
| start: token.start, | ||
| end: token.end | ||
| }); | ||
| return locations; | ||
| } | ||
| const ESM_RE = /(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m; | ||
| const CJS_RE = /(?:[\s;]|^)(?:module\.exports\b|exports\.\w|require\s*\(|global\.\w)/m; | ||
| const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g; | ||
| function hasESMSyntax(code, opts = {}) { | ||
| if (opts.stripComments) code = code.replace(COMMENT_RE, ""); | ||
| return ESM_RE.test(code); | ||
| } | ||
| function hasCJSSyntax(code, opts = {}) { | ||
| if (opts.stripComments) code = code.replace(COMMENT_RE, ""); | ||
| return CJS_RE.test(code); | ||
| } | ||
| function detectSyntax(code, opts = {}) { | ||
| if (opts.stripComments) code = code.replace(COMMENT_RE, ""); | ||
| const hasESM = hasESMSyntax(code, {}); | ||
| const hasCJS = hasCJSSyntax(code, {}); | ||
| return { | ||
| hasESM, | ||
| hasCJS, | ||
| isMixed: hasESM && hasCJS | ||
| }; | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/quansync@0.2.11/node_modules/quansync/dist/index.mjs | ||
| const GET_IS_ASYNC = Symbol.for("quansync.getIsAsync"); | ||
| var QuansyncError = class extends Error { | ||
| constructor(message = "Unexpected promise in sync context") { | ||
| super(message); | ||
| this.name = "QuansyncError"; | ||
| } | ||
| }; | ||
| function isThenable(value) { | ||
| return value && typeof value === "object" && typeof value.then === "function"; | ||
| } | ||
| function isQuansyncGenerator(value) { | ||
| return value && typeof value === "object" && typeof value[Symbol.iterator] === "function" && "__quansync" in value; | ||
| } | ||
| function fromObject(options) { | ||
| const generator = function* (...args) { | ||
| if (yield GET_IS_ASYNC) return yield options.async.apply(this, args); | ||
| return options.sync.apply(this, args); | ||
| }; | ||
| function fn(...args) { | ||
| const iter = generator.apply(this, args); | ||
| iter.then = (...thenArgs) => options.async.apply(this, args).then(...thenArgs); | ||
| iter.__quansync = true; | ||
| return iter; | ||
| } | ||
| fn.sync = options.sync; | ||
| fn.async = options.async; | ||
| return fn; | ||
| } | ||
| function fromPromise(promise) { | ||
| return fromObject({ | ||
| async: () => Promise.resolve(promise), | ||
| sync: () => { | ||
| if (isThenable(promise)) throw new QuansyncError(); | ||
| return promise; | ||
| } | ||
| }); | ||
| } | ||
| function unwrapYield(value, isAsync) { | ||
| if (value === GET_IS_ASYNC) return isAsync; | ||
| if (isQuansyncGenerator(value)) return isAsync ? iterateAsync(value) : iterateSync(value); | ||
| if (!isAsync && isThenable(value)) throw new QuansyncError(); | ||
| return value; | ||
| } | ||
| const DEFAULT_ON_YIELD = (value) => value; | ||
| function iterateSync(generator, onYield = DEFAULT_ON_YIELD) { | ||
| let current = generator.next(); | ||
| while (!current.done) try { | ||
| current = generator.next(unwrapYield(onYield(current.value, false))); | ||
| } catch (err) { | ||
| current = generator.throw(err); | ||
| } | ||
| return unwrapYield(current.value); | ||
| } | ||
| async function iterateAsync(generator, onYield = DEFAULT_ON_YIELD) { | ||
| let current = generator.next(); | ||
| while (!current.done) try { | ||
| current = generator.next(await unwrapYield(onYield(current.value, true), true)); | ||
| } catch (err) { | ||
| current = generator.throw(err); | ||
| } | ||
| return current.value; | ||
| } | ||
| function fromGeneratorFn(generatorFn, options) { | ||
| return fromObject({ | ||
| name: generatorFn.name, | ||
| async(...args) { | ||
| return iterateAsync(generatorFn.apply(this, args), options?.onYield); | ||
| }, | ||
| sync(...args) { | ||
| return iterateSync(generatorFn.apply(this, args), options?.onYield); | ||
| } | ||
| }); | ||
| } | ||
| function quansync$1(input, options) { | ||
| if (isThenable(input)) return fromPromise(input); | ||
| if (typeof input === "function") return fromGeneratorFn(input, options); | ||
| else return fromObject(input); | ||
| } | ||
| const getIsAsync = quansync$1({ | ||
| async: () => Promise.resolve(true), | ||
| sync: () => false | ||
| }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/quansync@0.2.11/node_modules/quansync/dist/macro.mjs | ||
| const quansync = quansync$1; | ||
| //#endregion | ||
| //#region node_modules/.pnpm/local-pkg@1.1.2/node_modules/local-pkg/dist/index.mjs | ||
| const toPath = (urlOrPath) => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath; | ||
| async function findUp$1(name, { cwd: cwd$1 = process$1.cwd(), type = "file", stopAt } = {}) { | ||
| let directory = path.resolve(toPath(cwd$1) ?? ""); | ||
| const { root } = path.parse(directory); | ||
| stopAt = path.resolve(directory, toPath(stopAt ?? root)); | ||
| const isAbsoluteName = path.isAbsolute(name); | ||
| while (directory) { | ||
| const filePath = isAbsoluteName ? name : path.join(directory, name); | ||
| try { | ||
| const stats = await fsp.stat(filePath); | ||
| if (type === "file" && stats.isFile() || type === "directory" && stats.isDirectory()) return filePath; | ||
| } catch {} | ||
| if (directory === stopAt || directory === root) break; | ||
| directory = path.dirname(directory); | ||
| } | ||
| } | ||
| function findUpSync(name, { cwd: cwd$1 = process$1.cwd(), type = "file", stopAt } = {}) { | ||
| let directory = path.resolve(toPath(cwd$1) ?? ""); | ||
| const { root } = path.parse(directory); | ||
| stopAt = path.resolve(directory, toPath(stopAt) ?? root); | ||
| const isAbsoluteName = path.isAbsolute(name); | ||
| while (directory) { | ||
| const filePath = isAbsoluteName ? name : path.join(directory, name); | ||
| try { | ||
| const stats = fs.statSync(filePath, { throwIfNoEntry: false }); | ||
| if (type === "file" && stats?.isFile() || type === "directory" && stats?.isDirectory()) return filePath; | ||
| } catch {} | ||
| if (directory === stopAt || directory === root) break; | ||
| directory = path.dirname(directory); | ||
| } | ||
| } | ||
| function _resolve(path$1, options = {}) { | ||
| if (options.platform === "auto" || !options.platform) options.platform = process$1.platform === "win32" ? "win32" : "posix"; | ||
| if (process$1.versions.pnp) { | ||
| const paths = options.paths || []; | ||
| if (paths.length === 0) paths.push(process$1.cwd()); | ||
| const targetRequire = createRequire(import.meta.url); | ||
| try { | ||
| return targetRequire.resolve(path$1, { paths }); | ||
| } catch {} | ||
| } | ||
| const modulePath = resolvePathSync(path$1, { url: options.paths }); | ||
| if (options.platform === "win32") return win32.normalize(modulePath); | ||
| return modulePath; | ||
| } | ||
| function resolveModule(name, options = {}) { | ||
| try { | ||
| return _resolve(name, options); | ||
| } catch { | ||
| return; | ||
| } | ||
| } | ||
| function getPackageJsonPath(name, options = {}) { | ||
| const entry = resolvePackage(name, options); | ||
| if (!entry) return; | ||
| return searchPackageJSON(entry); | ||
| } | ||
| const readFile$1 = quansync({ | ||
| async: (id) => fs.promises.readFile(id, "utf8"), | ||
| sync: (id) => fs.readFileSync(id, "utf8") | ||
| }); | ||
| const getPackageInfo = quansync(function* (name, options = {}) { | ||
| const packageJsonPath = getPackageJsonPath(name, options); | ||
| if (!packageJsonPath) return; | ||
| const packageJson = JSON.parse(yield readFile$1(packageJsonPath)); | ||
| return { | ||
| name, | ||
| version: packageJson.version, | ||
| rootPath: dirname(packageJsonPath), | ||
| packageJsonPath, | ||
| packageJson | ||
| }; | ||
| }); | ||
| const getPackageInfoSync = getPackageInfo.sync; | ||
| function resolvePackage(name, options = {}) { | ||
| try { | ||
| return _resolve(`${name}/package.json`, options); | ||
| } catch {} | ||
| try { | ||
| return _resolve(name, options); | ||
| } catch (e) { | ||
| if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ERR_MODULE_NOT_FOUND") console.error(e); | ||
| return false; | ||
| } | ||
| } | ||
| function searchPackageJSON(dir) { | ||
| let packageJsonPath; | ||
| while (true) { | ||
| if (!dir) return; | ||
| const newDir = dirname(dir); | ||
| if (newDir === dir) return; | ||
| dir = newDir; | ||
| packageJsonPath = join(dir, "package.json"); | ||
| if (fs.existsSync(packageJsonPath)) break; | ||
| } | ||
| return packageJsonPath; | ||
| } | ||
| const findUp = quansync({ | ||
| sync: findUpSync, | ||
| async: findUp$1 | ||
| }); | ||
| const loadPackageJSON = quansync(function* (cwd$1 = process$1.cwd()) { | ||
| const path$1 = yield findUp("package.json", { cwd: cwd$1 }); | ||
| if (!path$1 || !fs.existsSync(path$1)) return null; | ||
| return JSON.parse(yield readFile$1(path$1)); | ||
| }); | ||
| const loadPackageJSONSync = loadPackageJSON.sync; | ||
| const isPackageListed = quansync(function* (name, cwd$1) { | ||
| const pkg = (yield loadPackageJSON(cwd$1)) || {}; | ||
| return name in (pkg.dependencies || {}) || name in (pkg.devDependencies || {}); | ||
| }); | ||
| const isPackageListedSync = isPackageListed.sync; | ||
| //#endregion | ||
| export { findStaticImports as a, parseNodeModulePath as c, resolveModuleExportNames as d, sanitizeFilePath as f, findExports as i, parseStaticImport as l, detectSyntax as n, findTypeExports as o, fileURLToPath$1 as r, lookupNodeModuleSubpath as s, resolveModule as t, resolve$1 as u }; |
| import { u as encode } from "./gen-mapping.mjs"; | ||
| //#region node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs | ||
| var BitSet = class BitSet { | ||
| constructor(arg) { | ||
| this.bits = arg instanceof BitSet ? arg.bits.slice() : []; | ||
| } | ||
| add(n$1) { | ||
| this.bits[n$1 >> 5] |= 1 << (n$1 & 31); | ||
| } | ||
| has(n$1) { | ||
| return !!(this.bits[n$1 >> 5] & 1 << (n$1 & 31)); | ||
| } | ||
| }; | ||
| var Chunk = class Chunk { | ||
| constructor(start, end, content) { | ||
| this.start = start; | ||
| this.end = end; | ||
| this.original = content; | ||
| this.intro = ""; | ||
| this.outro = ""; | ||
| this.content = content; | ||
| this.storeName = false; | ||
| this.edited = false; | ||
| this.previous = null; | ||
| this.next = null; | ||
| } | ||
| appendLeft(content) { | ||
| this.outro += content; | ||
| } | ||
| appendRight(content) { | ||
| this.intro = this.intro + content; | ||
| } | ||
| clone() { | ||
| const chunk = new Chunk(this.start, this.end, this.original); | ||
| chunk.intro = this.intro; | ||
| chunk.outro = this.outro; | ||
| chunk.content = this.content; | ||
| chunk.storeName = this.storeName; | ||
| chunk.edited = this.edited; | ||
| return chunk; | ||
| } | ||
| contains(index) { | ||
| return this.start < index && index < this.end; | ||
| } | ||
| eachNext(fn) { | ||
| let chunk = this; | ||
| while (chunk) { | ||
| fn(chunk); | ||
| chunk = chunk.next; | ||
| } | ||
| } | ||
| eachPrevious(fn) { | ||
| let chunk = this; | ||
| while (chunk) { | ||
| fn(chunk); | ||
| chunk = chunk.previous; | ||
| } | ||
| } | ||
| edit(content, storeName, contentOnly) { | ||
| this.content = content; | ||
| if (!contentOnly) { | ||
| this.intro = ""; | ||
| this.outro = ""; | ||
| } | ||
| this.storeName = storeName; | ||
| this.edited = true; | ||
| return this; | ||
| } | ||
| prependLeft(content) { | ||
| this.outro = content + this.outro; | ||
| } | ||
| prependRight(content) { | ||
| this.intro = content + this.intro; | ||
| } | ||
| reset() { | ||
| this.intro = ""; | ||
| this.outro = ""; | ||
| if (this.edited) { | ||
| this.content = this.original; | ||
| this.storeName = false; | ||
| this.edited = false; | ||
| } | ||
| } | ||
| split(index) { | ||
| const sliceIndex = index - this.start; | ||
| const originalBefore = this.original.slice(0, sliceIndex); | ||
| const originalAfter = this.original.slice(sliceIndex); | ||
| this.original = originalBefore; | ||
| const newChunk = new Chunk(index, this.end, originalAfter); | ||
| newChunk.outro = this.outro; | ||
| this.outro = ""; | ||
| this.end = index; | ||
| if (this.edited) { | ||
| newChunk.edit("", false); | ||
| this.content = ""; | ||
| } else this.content = originalBefore; | ||
| newChunk.next = this.next; | ||
| if (newChunk.next) newChunk.next.previous = newChunk; | ||
| newChunk.previous = this; | ||
| this.next = newChunk; | ||
| return newChunk; | ||
| } | ||
| toString() { | ||
| return this.intro + this.content + this.outro; | ||
| } | ||
| trimEnd(rx) { | ||
| this.outro = this.outro.replace(rx, ""); | ||
| if (this.outro.length) return true; | ||
| const trimmed = this.content.replace(rx, ""); | ||
| if (trimmed.length) { | ||
| if (trimmed !== this.content) { | ||
| this.split(this.start + trimmed.length).edit("", void 0, true); | ||
| if (this.edited) this.edit(trimmed, this.storeName, true); | ||
| } | ||
| return true; | ||
| } else { | ||
| this.edit("", void 0, true); | ||
| this.intro = this.intro.replace(rx, ""); | ||
| if (this.intro.length) return true; | ||
| } | ||
| } | ||
| trimStart(rx) { | ||
| this.intro = this.intro.replace(rx, ""); | ||
| if (this.intro.length) return true; | ||
| const trimmed = this.content.replace(rx, ""); | ||
| if (trimmed.length) { | ||
| if (trimmed !== this.content) { | ||
| const newChunk = this.split(this.end - trimmed.length); | ||
| if (this.edited) newChunk.edit(trimmed, this.storeName, true); | ||
| this.edit("", void 0, true); | ||
| } | ||
| return true; | ||
| } else { | ||
| this.edit("", void 0, true); | ||
| this.outro = this.outro.replace(rx, ""); | ||
| if (this.outro.length) return true; | ||
| } | ||
| } | ||
| }; | ||
| function getBtoa() { | ||
| if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str))); | ||
| else if (typeof Buffer === "function") return (str) => Buffer.from(str, "utf-8").toString("base64"); | ||
| else return () => { | ||
| throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported."); | ||
| }; | ||
| } | ||
| const btoa = /* @__PURE__ */ getBtoa(); | ||
| var SourceMap = class { | ||
| constructor(properties) { | ||
| this.version = 3; | ||
| this.file = properties.file; | ||
| this.sources = properties.sources; | ||
| this.sourcesContent = properties.sourcesContent; | ||
| this.names = properties.names; | ||
| this.mappings = encode(properties.mappings); | ||
| if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList; | ||
| if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId; | ||
| } | ||
| toString() { | ||
| return JSON.stringify(this); | ||
| } | ||
| toUrl() { | ||
| return "data:application/json;charset=utf-8;base64," + btoa(this.toString()); | ||
| } | ||
| }; | ||
| function guessIndent(code) { | ||
| const lines = code.split("\n"); | ||
| const tabbed = lines.filter((line) => /^\t+/.test(line)); | ||
| const spaced = lines.filter((line) => /^ {2,}/.test(line)); | ||
| if (tabbed.length === 0 && spaced.length === 0) return null; | ||
| if (tabbed.length >= spaced.length) return " "; | ||
| const min = spaced.reduce((previous, current) => { | ||
| const numSpaces = /^ +/.exec(current)[0].length; | ||
| return Math.min(numSpaces, previous); | ||
| }, Infinity); | ||
| return new Array(min + 1).join(" "); | ||
| } | ||
| function getRelativePath(from, to) { | ||
| const fromParts = from.split(/[/\\]/); | ||
| const toParts = to.split(/[/\\]/); | ||
| fromParts.pop(); | ||
| while (fromParts[0] === toParts[0]) { | ||
| fromParts.shift(); | ||
| toParts.shift(); | ||
| } | ||
| if (fromParts.length) { | ||
| let i = fromParts.length; | ||
| while (i--) fromParts[i] = ".."; | ||
| } | ||
| return fromParts.concat(toParts).join("/"); | ||
| } | ||
| const toString = Object.prototype.toString; | ||
| function isObject(thing) { | ||
| return toString.call(thing) === "[object Object]"; | ||
| } | ||
| function getLocator(source) { | ||
| const originalLines = source.split("\n"); | ||
| const lineOffsets = []; | ||
| for (let i = 0, pos = 0; i < originalLines.length; i++) { | ||
| lineOffsets.push(pos); | ||
| pos += originalLines[i].length + 1; | ||
| } | ||
| return function locate(index) { | ||
| let i = 0; | ||
| let j = lineOffsets.length; | ||
| while (i < j) { | ||
| const m = i + j >> 1; | ||
| if (index < lineOffsets[m]) j = m; | ||
| else i = m + 1; | ||
| } | ||
| const line = i - 1; | ||
| return { | ||
| line, | ||
| column: index - lineOffsets[line] | ||
| }; | ||
| }; | ||
| } | ||
| const wordRegex = /\w/; | ||
| var Mappings = class { | ||
| constructor(hires) { | ||
| this.hires = hires; | ||
| this.generatedCodeLine = 0; | ||
| this.generatedCodeColumn = 0; | ||
| this.raw = []; | ||
| this.rawSegments = this.raw[this.generatedCodeLine] = []; | ||
| this.pending = null; | ||
| } | ||
| addEdit(sourceIndex, content, loc, nameIndex) { | ||
| if (content.length) { | ||
| const contentLengthMinusOne = content.length - 1; | ||
| let contentLineEnd = content.indexOf("\n", 0); | ||
| let previousContentLineEnd = -1; | ||
| while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) { | ||
| const segment$1 = [ | ||
| this.generatedCodeColumn, | ||
| sourceIndex, | ||
| loc.line, | ||
| loc.column | ||
| ]; | ||
| if (nameIndex >= 0) segment$1.push(nameIndex); | ||
| this.rawSegments.push(segment$1); | ||
| this.generatedCodeLine += 1; | ||
| this.raw[this.generatedCodeLine] = this.rawSegments = []; | ||
| this.generatedCodeColumn = 0; | ||
| previousContentLineEnd = contentLineEnd; | ||
| contentLineEnd = content.indexOf("\n", contentLineEnd + 1); | ||
| } | ||
| const segment = [ | ||
| this.generatedCodeColumn, | ||
| sourceIndex, | ||
| loc.line, | ||
| loc.column | ||
| ]; | ||
| if (nameIndex >= 0) segment.push(nameIndex); | ||
| this.rawSegments.push(segment); | ||
| this.advance(content.slice(previousContentLineEnd + 1)); | ||
| } else if (this.pending) { | ||
| this.rawSegments.push(this.pending); | ||
| this.advance(content); | ||
| } | ||
| this.pending = null; | ||
| } | ||
| addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { | ||
| let originalCharIndex = chunk.start; | ||
| let first = true; | ||
| let charInHiresBoundary = false; | ||
| while (originalCharIndex < chunk.end) { | ||
| if (original[originalCharIndex] === "\n") { | ||
| loc.line += 1; | ||
| loc.column = 0; | ||
| this.generatedCodeLine += 1; | ||
| this.raw[this.generatedCodeLine] = this.rawSegments = []; | ||
| this.generatedCodeColumn = 0; | ||
| first = true; | ||
| charInHiresBoundary = false; | ||
| } else { | ||
| if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { | ||
| const segment = [ | ||
| this.generatedCodeColumn, | ||
| sourceIndex, | ||
| loc.line, | ||
| loc.column | ||
| ]; | ||
| if (this.hires === "boundary") if (wordRegex.test(original[originalCharIndex])) { | ||
| if (!charInHiresBoundary) { | ||
| this.rawSegments.push(segment); | ||
| charInHiresBoundary = true; | ||
| } | ||
| } else { | ||
| this.rawSegments.push(segment); | ||
| charInHiresBoundary = false; | ||
| } | ||
| else this.rawSegments.push(segment); | ||
| } | ||
| loc.column += 1; | ||
| this.generatedCodeColumn += 1; | ||
| first = false; | ||
| } | ||
| originalCharIndex += 1; | ||
| } | ||
| this.pending = null; | ||
| } | ||
| advance(str) { | ||
| if (!str) return; | ||
| const lines = str.split("\n"); | ||
| if (lines.length > 1) { | ||
| for (let i = 0; i < lines.length - 1; i++) { | ||
| this.generatedCodeLine++; | ||
| this.raw[this.generatedCodeLine] = this.rawSegments = []; | ||
| } | ||
| this.generatedCodeColumn = 0; | ||
| } | ||
| this.generatedCodeColumn += lines[lines.length - 1].length; | ||
| } | ||
| }; | ||
| const n = "\n"; | ||
| const warned = { | ||
| insertLeft: false, | ||
| insertRight: false, | ||
| storeName: false | ||
| }; | ||
| var MagicString = class MagicString { | ||
| constructor(string, options = {}) { | ||
| const chunk = new Chunk(0, string.length, string); | ||
| Object.defineProperties(this, { | ||
| original: { | ||
| writable: true, | ||
| value: string | ||
| }, | ||
| outro: { | ||
| writable: true, | ||
| value: "" | ||
| }, | ||
| intro: { | ||
| writable: true, | ||
| value: "" | ||
| }, | ||
| firstChunk: { | ||
| writable: true, | ||
| value: chunk | ||
| }, | ||
| lastChunk: { | ||
| writable: true, | ||
| value: chunk | ||
| }, | ||
| lastSearchedChunk: { | ||
| writable: true, | ||
| value: chunk | ||
| }, | ||
| byStart: { | ||
| writable: true, | ||
| value: {} | ||
| }, | ||
| byEnd: { | ||
| writable: true, | ||
| value: {} | ||
| }, | ||
| filename: { | ||
| writable: true, | ||
| value: options.filename | ||
| }, | ||
| indentExclusionRanges: { | ||
| writable: true, | ||
| value: options.indentExclusionRanges | ||
| }, | ||
| sourcemapLocations: { | ||
| writable: true, | ||
| value: new BitSet() | ||
| }, | ||
| storedNames: { | ||
| writable: true, | ||
| value: {} | ||
| }, | ||
| indentStr: { | ||
| writable: true, | ||
| value: void 0 | ||
| }, | ||
| ignoreList: { | ||
| writable: true, | ||
| value: options.ignoreList | ||
| }, | ||
| offset: { | ||
| writable: true, | ||
| value: options.offset || 0 | ||
| } | ||
| }); | ||
| this.byStart[0] = chunk; | ||
| this.byEnd[string.length] = chunk; | ||
| } | ||
| addSourcemapLocation(char) { | ||
| this.sourcemapLocations.add(char); | ||
| } | ||
| append(content) { | ||
| if (typeof content !== "string") throw new TypeError("outro content must be a string"); | ||
| this.outro += content; | ||
| return this; | ||
| } | ||
| appendLeft(index, content) { | ||
| index = index + this.offset; | ||
| if (typeof content !== "string") throw new TypeError("inserted content must be a string"); | ||
| this._split(index); | ||
| const chunk = this.byEnd[index]; | ||
| if (chunk) chunk.appendLeft(content); | ||
| else this.intro += content; | ||
| return this; | ||
| } | ||
| appendRight(index, content) { | ||
| index = index + this.offset; | ||
| if (typeof content !== "string") throw new TypeError("inserted content must be a string"); | ||
| this._split(index); | ||
| const chunk = this.byStart[index]; | ||
| if (chunk) chunk.appendRight(content); | ||
| else this.outro += content; | ||
| return this; | ||
| } | ||
| clone() { | ||
| const cloned = new MagicString(this.original, { | ||
| filename: this.filename, | ||
| offset: this.offset | ||
| }); | ||
| let originalChunk = this.firstChunk; | ||
| let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone(); | ||
| while (originalChunk) { | ||
| cloned.byStart[clonedChunk.start] = clonedChunk; | ||
| cloned.byEnd[clonedChunk.end] = clonedChunk; | ||
| const nextOriginalChunk = originalChunk.next; | ||
| const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); | ||
| if (nextClonedChunk) { | ||
| clonedChunk.next = nextClonedChunk; | ||
| nextClonedChunk.previous = clonedChunk; | ||
| clonedChunk = nextClonedChunk; | ||
| } | ||
| originalChunk = nextOriginalChunk; | ||
| } | ||
| cloned.lastChunk = clonedChunk; | ||
| if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); | ||
| cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); | ||
| cloned.intro = this.intro; | ||
| cloned.outro = this.outro; | ||
| return cloned; | ||
| } | ||
| generateDecodedMap(options) { | ||
| options = options || {}; | ||
| const sourceIndex = 0; | ||
| const names = Object.keys(this.storedNames); | ||
| const mappings = new Mappings(options.hires); | ||
| const locate = getLocator(this.original); | ||
| if (this.intro) mappings.advance(this.intro); | ||
| this.firstChunk.eachNext((chunk) => { | ||
| const loc = locate(chunk.start); | ||
| if (chunk.intro.length) mappings.advance(chunk.intro); | ||
| if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1); | ||
| else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); | ||
| if (chunk.outro.length) mappings.advance(chunk.outro); | ||
| }); | ||
| if (this.outro) mappings.advance(this.outro); | ||
| return { | ||
| file: options.file ? options.file.split(/[/\\]/).pop() : void 0, | ||
| sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""], | ||
| sourcesContent: options.includeContent ? [this.original] : void 0, | ||
| names, | ||
| mappings: mappings.raw, | ||
| x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0 | ||
| }; | ||
| } | ||
| generateMap(options) { | ||
| return new SourceMap(this.generateDecodedMap(options)); | ||
| } | ||
| _ensureindentStr() { | ||
| if (this.indentStr === void 0) this.indentStr = guessIndent(this.original); | ||
| } | ||
| _getRawIndentString() { | ||
| this._ensureindentStr(); | ||
| return this.indentStr; | ||
| } | ||
| getIndentString() { | ||
| this._ensureindentStr(); | ||
| return this.indentStr === null ? " " : this.indentStr; | ||
| } | ||
| indent(indentStr, options) { | ||
| const pattern = /^[^\r\n]/gm; | ||
| if (isObject(indentStr)) { | ||
| options = indentStr; | ||
| indentStr = void 0; | ||
| } | ||
| if (indentStr === void 0) { | ||
| this._ensureindentStr(); | ||
| indentStr = this.indentStr || " "; | ||
| } | ||
| if (indentStr === "") return this; | ||
| options = options || {}; | ||
| const isExcluded = {}; | ||
| if (options.exclude) (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => { | ||
| for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded[i] = true; | ||
| }); | ||
| let shouldIndentNextCharacter = options.indentStart !== false; | ||
| const replacer = (match) => { | ||
| if (shouldIndentNextCharacter) return `${indentStr}${match}`; | ||
| shouldIndentNextCharacter = true; | ||
| return match; | ||
| }; | ||
| this.intro = this.intro.replace(pattern, replacer); | ||
| let charIndex = 0; | ||
| let chunk = this.firstChunk; | ||
| while (chunk) { | ||
| const end = chunk.end; | ||
| if (chunk.edited) { | ||
| if (!isExcluded[charIndex]) { | ||
| chunk.content = chunk.content.replace(pattern, replacer); | ||
| if (chunk.content.length) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n"; | ||
| } | ||
| } else { | ||
| charIndex = chunk.start; | ||
| while (charIndex < end) { | ||
| if (!isExcluded[charIndex]) { | ||
| const char = this.original[charIndex]; | ||
| if (char === "\n") shouldIndentNextCharacter = true; | ||
| else if (char !== "\r" && shouldIndentNextCharacter) { | ||
| shouldIndentNextCharacter = false; | ||
| if (charIndex === chunk.start) chunk.prependRight(indentStr); | ||
| else { | ||
| this._splitChunk(chunk, charIndex); | ||
| chunk = chunk.next; | ||
| chunk.prependRight(indentStr); | ||
| } | ||
| } | ||
| } | ||
| charIndex += 1; | ||
| } | ||
| } | ||
| charIndex = chunk.end; | ||
| chunk = chunk.next; | ||
| } | ||
| this.outro = this.outro.replace(pattern, replacer); | ||
| return this; | ||
| } | ||
| insert() { | ||
| throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)"); | ||
| } | ||
| insertLeft(index, content) { | ||
| if (!warned.insertLeft) { | ||
| console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"); | ||
| warned.insertLeft = true; | ||
| } | ||
| return this.appendLeft(index, content); | ||
| } | ||
| insertRight(index, content) { | ||
| if (!warned.insertRight) { | ||
| console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"); | ||
| warned.insertRight = true; | ||
| } | ||
| return this.prependRight(index, content); | ||
| } | ||
| move(start, end, index) { | ||
| start = start + this.offset; | ||
| end = end + this.offset; | ||
| index = index + this.offset; | ||
| if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself"); | ||
| this._split(start); | ||
| this._split(end); | ||
| this._split(index); | ||
| const first = this.byStart[start]; | ||
| const last = this.byEnd[end]; | ||
| const oldLeft = first.previous; | ||
| const oldRight = last.next; | ||
| const newRight = this.byStart[index]; | ||
| if (!newRight && last === this.lastChunk) return this; | ||
| const newLeft = newRight ? newRight.previous : this.lastChunk; | ||
| if (oldLeft) oldLeft.next = oldRight; | ||
| if (oldRight) oldRight.previous = oldLeft; | ||
| if (newLeft) newLeft.next = first; | ||
| if (newRight) newRight.previous = last; | ||
| if (!first.previous) this.firstChunk = last.next; | ||
| if (!last.next) { | ||
| this.lastChunk = first.previous; | ||
| this.lastChunk.next = null; | ||
| } | ||
| first.previous = newLeft; | ||
| last.next = newRight || null; | ||
| if (!newLeft) this.firstChunk = first; | ||
| if (!newRight) this.lastChunk = last; | ||
| return this; | ||
| } | ||
| overwrite(start, end, content, options) { | ||
| options = options || {}; | ||
| return this.update(start, end, content, { | ||
| ...options, | ||
| overwrite: !options.contentOnly | ||
| }); | ||
| } | ||
| update(start, end, content, options) { | ||
| start = start + this.offset; | ||
| end = end + this.offset; | ||
| if (typeof content !== "string") throw new TypeError("replacement content must be a string"); | ||
| if (this.original.length !== 0) { | ||
| while (start < 0) start += this.original.length; | ||
| while (end < 0) end += this.original.length; | ||
| } | ||
| if (end > this.original.length) throw new Error("end is out of bounds"); | ||
| if (start === end) throw new Error("Cannot overwrite a zero-length range – use appendLeft or prependRight instead"); | ||
| this._split(start); | ||
| this._split(end); | ||
| if (options === true) { | ||
| if (!warned.storeName) { | ||
| console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"); | ||
| warned.storeName = true; | ||
| } | ||
| options = { storeName: true }; | ||
| } | ||
| const storeName = options !== void 0 ? options.storeName : false; | ||
| const overwrite = options !== void 0 ? options.overwrite : false; | ||
| if (storeName) { | ||
| const original = this.original.slice(start, end); | ||
| Object.defineProperty(this.storedNames, original, { | ||
| writable: true, | ||
| value: true, | ||
| enumerable: true | ||
| }); | ||
| } | ||
| const first = this.byStart[start]; | ||
| const last = this.byEnd[end]; | ||
| if (first) { | ||
| let chunk = first; | ||
| while (chunk !== last) { | ||
| if (chunk.next !== this.byStart[chunk.end]) throw new Error("Cannot overwrite across a split point"); | ||
| chunk = chunk.next; | ||
| chunk.edit("", false); | ||
| } | ||
| first.edit(content, storeName, !overwrite); | ||
| } else { | ||
| const newChunk = new Chunk(start, end, "").edit(content, storeName); | ||
| last.next = newChunk; | ||
| newChunk.previous = last; | ||
| } | ||
| return this; | ||
| } | ||
| prepend(content) { | ||
| if (typeof content !== "string") throw new TypeError("outro content must be a string"); | ||
| this.intro = content + this.intro; | ||
| return this; | ||
| } | ||
| prependLeft(index, content) { | ||
| index = index + this.offset; | ||
| if (typeof content !== "string") throw new TypeError("inserted content must be a string"); | ||
| this._split(index); | ||
| const chunk = this.byEnd[index]; | ||
| if (chunk) chunk.prependLeft(content); | ||
| else this.intro = content + this.intro; | ||
| return this; | ||
| } | ||
| prependRight(index, content) { | ||
| index = index + this.offset; | ||
| if (typeof content !== "string") throw new TypeError("inserted content must be a string"); | ||
| this._split(index); | ||
| const chunk = this.byStart[index]; | ||
| if (chunk) chunk.prependRight(content); | ||
| else this.outro = content + this.outro; | ||
| return this; | ||
| } | ||
| remove(start, end) { | ||
| start = start + this.offset; | ||
| end = end + this.offset; | ||
| if (this.original.length !== 0) { | ||
| while (start < 0) start += this.original.length; | ||
| while (end < 0) end += this.original.length; | ||
| } | ||
| if (start === end) return this; | ||
| if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds"); | ||
| if (start > end) throw new Error("end must be greater than start"); | ||
| this._split(start); | ||
| this._split(end); | ||
| let chunk = this.byStart[start]; | ||
| while (chunk) { | ||
| chunk.intro = ""; | ||
| chunk.outro = ""; | ||
| chunk.edit(""); | ||
| chunk = end > chunk.end ? this.byStart[chunk.end] : null; | ||
| } | ||
| return this; | ||
| } | ||
| reset(start, end) { | ||
| start = start + this.offset; | ||
| end = end + this.offset; | ||
| if (this.original.length !== 0) { | ||
| while (start < 0) start += this.original.length; | ||
| while (end < 0) end += this.original.length; | ||
| } | ||
| if (start === end) return this; | ||
| if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds"); | ||
| if (start > end) throw new Error("end must be greater than start"); | ||
| this._split(start); | ||
| this._split(end); | ||
| let chunk = this.byStart[start]; | ||
| while (chunk) { | ||
| chunk.reset(); | ||
| chunk = end > chunk.end ? this.byStart[chunk.end] : null; | ||
| } | ||
| return this; | ||
| } | ||
| lastChar() { | ||
| if (this.outro.length) return this.outro[this.outro.length - 1]; | ||
| let chunk = this.lastChunk; | ||
| do { | ||
| if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; | ||
| if (chunk.content.length) return chunk.content[chunk.content.length - 1]; | ||
| if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; | ||
| } while (chunk = chunk.previous); | ||
| if (this.intro.length) return this.intro[this.intro.length - 1]; | ||
| return ""; | ||
| } | ||
| lastLine() { | ||
| let lineIndex = this.outro.lastIndexOf(n); | ||
| if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); | ||
| let lineStr = this.outro; | ||
| let chunk = this.lastChunk; | ||
| do { | ||
| if (chunk.outro.length > 0) { | ||
| lineIndex = chunk.outro.lastIndexOf(n); | ||
| if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; | ||
| lineStr = chunk.outro + lineStr; | ||
| } | ||
| if (chunk.content.length > 0) { | ||
| lineIndex = chunk.content.lastIndexOf(n); | ||
| if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; | ||
| lineStr = chunk.content + lineStr; | ||
| } | ||
| if (chunk.intro.length > 0) { | ||
| lineIndex = chunk.intro.lastIndexOf(n); | ||
| if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; | ||
| lineStr = chunk.intro + lineStr; | ||
| } | ||
| } while (chunk = chunk.previous); | ||
| lineIndex = this.intro.lastIndexOf(n); | ||
| if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; | ||
| return this.intro + lineStr; | ||
| } | ||
| slice(start = 0, end = this.original.length - this.offset) { | ||
| start = start + this.offset; | ||
| end = end + this.offset; | ||
| if (this.original.length !== 0) { | ||
| while (start < 0) start += this.original.length; | ||
| while (end < 0) end += this.original.length; | ||
| } | ||
| let result = ""; | ||
| let chunk = this.firstChunk; | ||
| while (chunk && (chunk.start > start || chunk.end <= start)) { | ||
| if (chunk.start < end && chunk.end >= end) return result; | ||
| chunk = chunk.next; | ||
| } | ||
| if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); | ||
| const startChunk = chunk; | ||
| while (chunk) { | ||
| if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro; | ||
| const containsEnd = chunk.start < end && chunk.end >= end; | ||
| if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); | ||
| const sliceStart = startChunk === chunk ? start - chunk.start : 0; | ||
| const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; | ||
| result += chunk.content.slice(sliceStart, sliceEnd); | ||
| if (chunk.outro && (!containsEnd || chunk.end === end)) result += chunk.outro; | ||
| if (containsEnd) break; | ||
| chunk = chunk.next; | ||
| } | ||
| return result; | ||
| } | ||
| snip(start, end) { | ||
| const clone = this.clone(); | ||
| clone.remove(0, start); | ||
| clone.remove(end, clone.original.length); | ||
| return clone; | ||
| } | ||
| _split(index) { | ||
| if (this.byStart[index] || this.byEnd[index]) return; | ||
| let chunk = this.lastSearchedChunk; | ||
| let previousChunk = chunk; | ||
| const searchForward = index > chunk.end; | ||
| while (chunk) { | ||
| if (chunk.contains(index)) return this._splitChunk(chunk, index); | ||
| chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; | ||
| if (chunk === previousChunk) return; | ||
| previousChunk = chunk; | ||
| } | ||
| } | ||
| _splitChunk(chunk, index) { | ||
| if (chunk.edited && chunk.content.length) { | ||
| const loc = getLocator(this.original)(index); | ||
| throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`); | ||
| } | ||
| const newChunk = chunk.split(index); | ||
| this.byEnd[index] = chunk; | ||
| this.byStart[index] = newChunk; | ||
| this.byEnd[newChunk.end] = newChunk; | ||
| if (chunk === this.lastChunk) this.lastChunk = newChunk; | ||
| this.lastSearchedChunk = chunk; | ||
| return true; | ||
| } | ||
| toString() { | ||
| let str = this.intro; | ||
| let chunk = this.firstChunk; | ||
| while (chunk) { | ||
| str += chunk.toString(); | ||
| chunk = chunk.next; | ||
| } | ||
| return str + this.outro; | ||
| } | ||
| isEmpty() { | ||
| let chunk = this.firstChunk; | ||
| do | ||
| if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false; | ||
| while (chunk = chunk.next); | ||
| return true; | ||
| } | ||
| length() { | ||
| let chunk = this.firstChunk; | ||
| let length = 0; | ||
| do | ||
| length += chunk.intro.length + chunk.content.length + chunk.outro.length; | ||
| while (chunk = chunk.next); | ||
| return length; | ||
| } | ||
| trimLines() { | ||
| return this.trim("[\\r\\n]"); | ||
| } | ||
| trim(charType) { | ||
| return this.trimStart(charType).trimEnd(charType); | ||
| } | ||
| trimEndAborted(charType) { | ||
| const rx = /* @__PURE__ */ new RegExp((charType || "\\s") + "+$"); | ||
| this.outro = this.outro.replace(rx, ""); | ||
| if (this.outro.length) return true; | ||
| let chunk = this.lastChunk; | ||
| do { | ||
| const end = chunk.end; | ||
| const aborted = chunk.trimEnd(rx); | ||
| if (chunk.end !== end) { | ||
| if (this.lastChunk === chunk) this.lastChunk = chunk.next; | ||
| this.byEnd[chunk.end] = chunk; | ||
| this.byStart[chunk.next.start] = chunk.next; | ||
| this.byEnd[chunk.next.end] = chunk.next; | ||
| } | ||
| if (aborted) return true; | ||
| chunk = chunk.previous; | ||
| } while (chunk); | ||
| return false; | ||
| } | ||
| trimEnd(charType) { | ||
| this.trimEndAborted(charType); | ||
| return this; | ||
| } | ||
| trimStartAborted(charType) { | ||
| const rx = /* @__PURE__ */ new RegExp("^" + (charType || "\\s") + "+"); | ||
| this.intro = this.intro.replace(rx, ""); | ||
| if (this.intro.length) return true; | ||
| let chunk = this.firstChunk; | ||
| do { | ||
| const end = chunk.end; | ||
| const aborted = chunk.trimStart(rx); | ||
| if (chunk.end !== end) { | ||
| if (chunk === this.lastChunk) this.lastChunk = chunk.next; | ||
| this.byEnd[chunk.end] = chunk; | ||
| this.byStart[chunk.next.start] = chunk.next; | ||
| this.byEnd[chunk.next.end] = chunk.next; | ||
| } | ||
| if (aborted) return true; | ||
| chunk = chunk.next; | ||
| } while (chunk); | ||
| return false; | ||
| } | ||
| trimStart(charType) { | ||
| this.trimStartAborted(charType); | ||
| return this; | ||
| } | ||
| hasChanged() { | ||
| return this.original !== this.toString(); | ||
| } | ||
| _replaceRegexp(searchValue, replacement) { | ||
| function getReplacement(match, str) { | ||
| if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { | ||
| if (i === "$") return "$"; | ||
| if (i === "&") return match[0]; | ||
| if (+i < match.length) return match[+i]; | ||
| return `$${i}`; | ||
| }); | ||
| else return replacement(...match, match.index, str, match.groups); | ||
| } | ||
| function matchAll(re, str) { | ||
| let match; | ||
| const matches = []; | ||
| while (match = re.exec(str)) matches.push(match); | ||
| return matches; | ||
| } | ||
| if (searchValue.global) matchAll(searchValue, this.original).forEach((match) => { | ||
| if (match.index != null) { | ||
| const replacement$1 = getReplacement(match, this.original); | ||
| if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1); | ||
| } | ||
| }); | ||
| else { | ||
| const match = this.original.match(searchValue); | ||
| if (match && match.index != null) { | ||
| const replacement$1 = getReplacement(match, this.original); | ||
| if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1); | ||
| } | ||
| } | ||
| return this; | ||
| } | ||
| _replaceString(string, replacement) { | ||
| const { original } = this; | ||
| const index = original.indexOf(string); | ||
| if (index !== -1) { | ||
| if (typeof replacement === "function") replacement = replacement(string, index, original); | ||
| if (string !== replacement) this.overwrite(index, index + string.length, replacement); | ||
| } | ||
| return this; | ||
| } | ||
| replace(searchValue, replacement) { | ||
| if (typeof searchValue === "string") return this._replaceString(searchValue, replacement); | ||
| return this._replaceRegexp(searchValue, replacement); | ||
| } | ||
| _replaceAllString(string, replacement) { | ||
| const { original } = this; | ||
| const stringLength = string.length; | ||
| for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) { | ||
| const previous = original.slice(index, index + stringLength); | ||
| let _replacement = replacement; | ||
| if (typeof replacement === "function") _replacement = replacement(previous, index, original); | ||
| if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement); | ||
| } | ||
| return this; | ||
| } | ||
| replaceAll(searchValue, replacement) { | ||
| if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement); | ||
| if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument"); | ||
| return this._replaceRegexp(searchValue, replacement); | ||
| } | ||
| }; | ||
| //#endregion | ||
| export { MagicString as t }; |
-1391
| //#region node_modules/.pnpm/mime@4.1.0/node_modules/mime/dist/types/other.js | ||
| const types$1 = { | ||
| "application/prs.cww": ["cww"], | ||
| "application/prs.xsf+xml": ["xsf"], | ||
| "application/vnd.1000minds.decision-model+xml": ["1km"], | ||
| "application/vnd.3gpp.pic-bw-large": ["plb"], | ||
| "application/vnd.3gpp.pic-bw-small": ["psb"], | ||
| "application/vnd.3gpp.pic-bw-var": ["pvb"], | ||
| "application/vnd.3gpp2.tcap": ["tcap"], | ||
| "application/vnd.3m.post-it-notes": ["pwn"], | ||
| "application/vnd.accpac.simply.aso": ["aso"], | ||
| "application/vnd.accpac.simply.imp": ["imp"], | ||
| "application/vnd.acucobol": ["acu"], | ||
| "application/vnd.acucorp": ["atc", "acutc"], | ||
| "application/vnd.adobe.air-application-installer-package+zip": ["air"], | ||
| "application/vnd.adobe.formscentral.fcdt": ["fcdt"], | ||
| "application/vnd.adobe.fxp": ["fxp", "fxpl"], | ||
| "application/vnd.adobe.xdp+xml": ["xdp"], | ||
| "application/vnd.adobe.xfdf": ["*xfdf"], | ||
| "application/vnd.age": ["age"], | ||
| "application/vnd.ahead.space": ["ahead"], | ||
| "application/vnd.airzip.filesecure.azf": ["azf"], | ||
| "application/vnd.airzip.filesecure.azs": ["azs"], | ||
| "application/vnd.amazon.ebook": ["azw"], | ||
| "application/vnd.americandynamics.acc": ["acc"], | ||
| "application/vnd.amiga.ami": ["ami"], | ||
| "application/vnd.android.package-archive": ["apk"], | ||
| "application/vnd.anser-web-certificate-issue-initiation": ["cii"], | ||
| "application/vnd.anser-web-funds-transfer-initiation": ["fti"], | ||
| "application/vnd.antix.game-component": ["atx"], | ||
| "application/vnd.apple.installer+xml": ["mpkg"], | ||
| "application/vnd.apple.keynote": ["key"], | ||
| "application/vnd.apple.mpegurl": ["m3u8"], | ||
| "application/vnd.apple.numbers": ["numbers"], | ||
| "application/vnd.apple.pages": ["pages"], | ||
| "application/vnd.apple.pkpass": ["pkpass"], | ||
| "application/vnd.aristanetworks.swi": ["swi"], | ||
| "application/vnd.astraea-software.iota": ["iota"], | ||
| "application/vnd.audiograph": ["aep"], | ||
| "application/vnd.autodesk.fbx": ["fbx"], | ||
| "application/vnd.balsamiq.bmml+xml": ["bmml"], | ||
| "application/vnd.blueice.multipass": ["mpm"], | ||
| "application/vnd.bmi": ["bmi"], | ||
| "application/vnd.businessobjects": ["rep"], | ||
| "application/vnd.chemdraw+xml": ["cdxml"], | ||
| "application/vnd.chipnuts.karaoke-mmd": ["mmd"], | ||
| "application/vnd.cinderella": ["cdy"], | ||
| "application/vnd.citationstyles.style+xml": ["csl"], | ||
| "application/vnd.claymore": ["cla"], | ||
| "application/vnd.cloanto.rp9": ["rp9"], | ||
| "application/vnd.clonk.c4group": [ | ||
| "c4g", | ||
| "c4d", | ||
| "c4f", | ||
| "c4p", | ||
| "c4u" | ||
| ], | ||
| "application/vnd.cluetrust.cartomobile-config": ["c11amc"], | ||
| "application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"], | ||
| "application/vnd.commonspace": ["csp"], | ||
| "application/vnd.contact.cmsg": ["cdbcmsg"], | ||
| "application/vnd.cosmocaller": ["cmc"], | ||
| "application/vnd.crick.clicker": ["clkx"], | ||
| "application/vnd.crick.clicker.keyboard": ["clkk"], | ||
| "application/vnd.crick.clicker.palette": ["clkp"], | ||
| "application/vnd.crick.clicker.template": ["clkt"], | ||
| "application/vnd.crick.clicker.wordbank": ["clkw"], | ||
| "application/vnd.criticaltools.wbs+xml": ["wbs"], | ||
| "application/vnd.ctc-posml": ["pml"], | ||
| "application/vnd.cups-ppd": ["ppd"], | ||
| "application/vnd.curl.car": ["car"], | ||
| "application/vnd.curl.pcurl": ["pcurl"], | ||
| "application/vnd.dart": ["dart"], | ||
| "application/vnd.data-vision.rdz": ["rdz"], | ||
| "application/vnd.dbf": ["dbf"], | ||
| "application/vnd.dcmp+xml": ["dcmp"], | ||
| "application/vnd.dece.data": [ | ||
| "uvf", | ||
| "uvvf", | ||
| "uvd", | ||
| "uvvd" | ||
| ], | ||
| "application/vnd.dece.ttml+xml": ["uvt", "uvvt"], | ||
| "application/vnd.dece.unspecified": ["uvx", "uvvx"], | ||
| "application/vnd.dece.zip": ["uvz", "uvvz"], | ||
| "application/vnd.denovo.fcselayout-link": ["fe_launch"], | ||
| "application/vnd.dna": ["dna"], | ||
| "application/vnd.dolby.mlp": ["mlp"], | ||
| "application/vnd.dpgraph": ["dpg"], | ||
| "application/vnd.dreamfactory": ["dfac"], | ||
| "application/vnd.ds-keypoint": ["kpxx"], | ||
| "application/vnd.dvb.ait": ["ait"], | ||
| "application/vnd.dvb.service": ["svc"], | ||
| "application/vnd.dynageo": ["geo"], | ||
| "application/vnd.ecowin.chart": ["mag"], | ||
| "application/vnd.enliven": ["nml"], | ||
| "application/vnd.epson.esf": ["esf"], | ||
| "application/vnd.epson.msf": ["msf"], | ||
| "application/vnd.epson.quickanime": ["qam"], | ||
| "application/vnd.epson.salt": ["slt"], | ||
| "application/vnd.epson.ssf": ["ssf"], | ||
| "application/vnd.eszigno3+xml": ["es3", "et3"], | ||
| "application/vnd.ezpix-album": ["ez2"], | ||
| "application/vnd.ezpix-package": ["ez3"], | ||
| "application/vnd.fdf": ["*fdf"], | ||
| "application/vnd.fdsn.mseed": ["mseed"], | ||
| "application/vnd.fdsn.seed": ["seed", "dataless"], | ||
| "application/vnd.flographit": ["gph"], | ||
| "application/vnd.fluxtime.clip": ["ftc"], | ||
| "application/vnd.framemaker": [ | ||
| "fm", | ||
| "frame", | ||
| "maker", | ||
| "book" | ||
| ], | ||
| "application/vnd.frogans.fnc": ["fnc"], | ||
| "application/vnd.frogans.ltf": ["ltf"], | ||
| "application/vnd.fsc.weblaunch": ["fsc"], | ||
| "application/vnd.fujitsu.oasys": ["oas"], | ||
| "application/vnd.fujitsu.oasys2": ["oa2"], | ||
| "application/vnd.fujitsu.oasys3": ["oa3"], | ||
| "application/vnd.fujitsu.oasysgp": ["fg5"], | ||
| "application/vnd.fujitsu.oasysprs": ["bh2"], | ||
| "application/vnd.fujixerox.ddd": ["ddd"], | ||
| "application/vnd.fujixerox.docuworks": ["xdw"], | ||
| "application/vnd.fujixerox.docuworks.binder": ["xbd"], | ||
| "application/vnd.fuzzysheet": ["fzs"], | ||
| "application/vnd.genomatix.tuxedo": ["txd"], | ||
| "application/vnd.geogebra.file": ["ggb"], | ||
| "application/vnd.geogebra.slides": ["ggs"], | ||
| "application/vnd.geogebra.tool": ["ggt"], | ||
| "application/vnd.geometry-explorer": ["gex", "gre"], | ||
| "application/vnd.geonext": ["gxt"], | ||
| "application/vnd.geoplan": ["g2w"], | ||
| "application/vnd.geospace": ["g3w"], | ||
| "application/vnd.gmx": ["gmx"], | ||
| "application/vnd.google-apps.document": ["gdoc"], | ||
| "application/vnd.google-apps.drawing": ["gdraw"], | ||
| "application/vnd.google-apps.form": ["gform"], | ||
| "application/vnd.google-apps.jam": ["gjam"], | ||
| "application/vnd.google-apps.map": ["gmap"], | ||
| "application/vnd.google-apps.presentation": ["gslides"], | ||
| "application/vnd.google-apps.script": ["gscript"], | ||
| "application/vnd.google-apps.site": ["gsite"], | ||
| "application/vnd.google-apps.spreadsheet": ["gsheet"], | ||
| "application/vnd.google-earth.kml+xml": ["kml"], | ||
| "application/vnd.google-earth.kmz": ["kmz"], | ||
| "application/vnd.gov.sk.xmldatacontainer+xml": ["xdcf"], | ||
| "application/vnd.grafeq": ["gqf", "gqs"], | ||
| "application/vnd.groove-account": ["gac"], | ||
| "application/vnd.groove-help": ["ghf"], | ||
| "application/vnd.groove-identity-message": ["gim"], | ||
| "application/vnd.groove-injector": ["grv"], | ||
| "application/vnd.groove-tool-message": ["gtm"], | ||
| "application/vnd.groove-tool-template": ["tpl"], | ||
| "application/vnd.groove-vcard": ["vcg"], | ||
| "application/vnd.hal+xml": ["hal"], | ||
| "application/vnd.handheld-entertainment+xml": ["zmm"], | ||
| "application/vnd.hbci": ["hbci"], | ||
| "application/vnd.hhe.lesson-player": ["les"], | ||
| "application/vnd.hp-hpgl": ["hpgl"], | ||
| "application/vnd.hp-hpid": ["hpid"], | ||
| "application/vnd.hp-hps": ["hps"], | ||
| "application/vnd.hp-jlyt": ["jlt"], | ||
| "application/vnd.hp-pcl": ["pcl"], | ||
| "application/vnd.hp-pclxl": ["pclxl"], | ||
| "application/vnd.hydrostatix.sof-data": ["sfd-hdstx"], | ||
| "application/vnd.ibm.minipay": ["mpy"], | ||
| "application/vnd.ibm.modcap": [ | ||
| "afp", | ||
| "listafp", | ||
| "list3820" | ||
| ], | ||
| "application/vnd.ibm.rights-management": ["irm"], | ||
| "application/vnd.ibm.secure-container": ["sc"], | ||
| "application/vnd.iccprofile": ["icc", "icm"], | ||
| "application/vnd.igloader": ["igl"], | ||
| "application/vnd.immervision-ivp": ["ivp"], | ||
| "application/vnd.immervision-ivu": ["ivu"], | ||
| "application/vnd.insors.igm": ["igm"], | ||
| "application/vnd.intercon.formnet": ["xpw", "xpx"], | ||
| "application/vnd.intergeo": ["i2g"], | ||
| "application/vnd.intu.qbo": ["qbo"], | ||
| "application/vnd.intu.qfx": ["qfx"], | ||
| "application/vnd.ipunplugged.rcprofile": ["rcprofile"], | ||
| "application/vnd.irepository.package+xml": ["irp"], | ||
| "application/vnd.is-xpr": ["xpr"], | ||
| "application/vnd.isac.fcs": ["fcs"], | ||
| "application/vnd.jam": ["jam"], | ||
| "application/vnd.jcp.javame.midlet-rms": ["rms"], | ||
| "application/vnd.jisp": ["jisp"], | ||
| "application/vnd.joost.joda-archive": ["joda"], | ||
| "application/vnd.kahootz": ["ktz", "ktr"], | ||
| "application/vnd.kde.karbon": ["karbon"], | ||
| "application/vnd.kde.kchart": ["chrt"], | ||
| "application/vnd.kde.kformula": ["kfo"], | ||
| "application/vnd.kde.kivio": ["flw"], | ||
| "application/vnd.kde.kontour": ["kon"], | ||
| "application/vnd.kde.kpresenter": ["kpr", "kpt"], | ||
| "application/vnd.kde.kspread": ["ksp"], | ||
| "application/vnd.kde.kword": ["kwd", "kwt"], | ||
| "application/vnd.kenameaapp": ["htke"], | ||
| "application/vnd.kidspiration": ["kia"], | ||
| "application/vnd.kinar": ["kne", "knp"], | ||
| "application/vnd.koan": [ | ||
| "skp", | ||
| "skd", | ||
| "skt", | ||
| "skm" | ||
| ], | ||
| "application/vnd.kodak-descriptor": ["sse"], | ||
| "application/vnd.las.las+xml": ["lasxml"], | ||
| "application/vnd.llamagraphics.life-balance.desktop": ["lbd"], | ||
| "application/vnd.llamagraphics.life-balance.exchange+xml": ["lbe"], | ||
| "application/vnd.lotus-1-2-3": ["123"], | ||
| "application/vnd.lotus-approach": ["apr"], | ||
| "application/vnd.lotus-freelance": ["pre"], | ||
| "application/vnd.lotus-notes": ["nsf"], | ||
| "application/vnd.lotus-organizer": ["org"], | ||
| "application/vnd.lotus-screencam": ["scm"], | ||
| "application/vnd.lotus-wordpro": ["lwp"], | ||
| "application/vnd.macports.portpkg": ["portpkg"], | ||
| "application/vnd.mapbox-vector-tile": ["mvt"], | ||
| "application/vnd.mcd": ["mcd"], | ||
| "application/vnd.medcalcdata": ["mc1"], | ||
| "application/vnd.mediastation.cdkey": ["cdkey"], | ||
| "application/vnd.mfer": ["mwf"], | ||
| "application/vnd.mfmp": ["mfm"], | ||
| "application/vnd.micrografx.flo": ["flo"], | ||
| "application/vnd.micrografx.igx": ["igx"], | ||
| "application/vnd.mif": ["mif"], | ||
| "application/vnd.mobius.daf": ["daf"], | ||
| "application/vnd.mobius.dis": ["dis"], | ||
| "application/vnd.mobius.mbk": ["mbk"], | ||
| "application/vnd.mobius.mqy": ["mqy"], | ||
| "application/vnd.mobius.msl": ["msl"], | ||
| "application/vnd.mobius.plc": ["plc"], | ||
| "application/vnd.mobius.txf": ["txf"], | ||
| "application/vnd.mophun.application": ["mpn"], | ||
| "application/vnd.mophun.certificate": ["mpc"], | ||
| "application/vnd.mozilla.xul+xml": ["xul"], | ||
| "application/vnd.ms-artgalry": ["cil"], | ||
| "application/vnd.ms-cab-compressed": ["cab"], | ||
| "application/vnd.ms-excel": [ | ||
| "xls", | ||
| "xlm", | ||
| "xla", | ||
| "xlc", | ||
| "xlt", | ||
| "xlw" | ||
| ], | ||
| "application/vnd.ms-excel.addin.macroenabled.12": ["xlam"], | ||
| "application/vnd.ms-excel.sheet.binary.macroenabled.12": ["xlsb"], | ||
| "application/vnd.ms-excel.sheet.macroenabled.12": ["xlsm"], | ||
| "application/vnd.ms-excel.template.macroenabled.12": ["xltm"], | ||
| "application/vnd.ms-fontobject": ["eot"], | ||
| "application/vnd.ms-htmlhelp": ["chm"], | ||
| "application/vnd.ms-ims": ["ims"], | ||
| "application/vnd.ms-lrm": ["lrm"], | ||
| "application/vnd.ms-officetheme": ["thmx"], | ||
| "application/vnd.ms-outlook": ["msg"], | ||
| "application/vnd.ms-pki.seccat": ["cat"], | ||
| "application/vnd.ms-pki.stl": ["*stl"], | ||
| "application/vnd.ms-powerpoint": [ | ||
| "ppt", | ||
| "pps", | ||
| "pot" | ||
| ], | ||
| "application/vnd.ms-powerpoint.addin.macroenabled.12": ["ppam"], | ||
| "application/vnd.ms-powerpoint.presentation.macroenabled.12": ["pptm"], | ||
| "application/vnd.ms-powerpoint.slide.macroenabled.12": ["sldm"], | ||
| "application/vnd.ms-powerpoint.slideshow.macroenabled.12": ["ppsm"], | ||
| "application/vnd.ms-powerpoint.template.macroenabled.12": ["potm"], | ||
| "application/vnd.ms-project": ["*mpp", "mpt"], | ||
| "application/vnd.ms-visio.viewer": ["vdx"], | ||
| "application/vnd.ms-word.document.macroenabled.12": ["docm"], | ||
| "application/vnd.ms-word.template.macroenabled.12": ["dotm"], | ||
| "application/vnd.ms-works": [ | ||
| "wps", | ||
| "wks", | ||
| "wcm", | ||
| "wdb" | ||
| ], | ||
| "application/vnd.ms-wpl": ["wpl"], | ||
| "application/vnd.ms-xpsdocument": ["xps"], | ||
| "application/vnd.mseq": ["mseq"], | ||
| "application/vnd.musician": ["mus"], | ||
| "application/vnd.muvee.style": ["msty"], | ||
| "application/vnd.mynfc": ["taglet"], | ||
| "application/vnd.nato.bindingdataobject+xml": ["bdo"], | ||
| "application/vnd.neurolanguage.nlu": ["nlu"], | ||
| "application/vnd.nitf": ["ntf", "nitf"], | ||
| "application/vnd.noblenet-directory": ["nnd"], | ||
| "application/vnd.noblenet-sealer": ["nns"], | ||
| "application/vnd.noblenet-web": ["nnw"], | ||
| "application/vnd.nokia.n-gage.ac+xml": ["*ac"], | ||
| "application/vnd.nokia.n-gage.data": ["ngdat"], | ||
| "application/vnd.nokia.n-gage.symbian.install": ["n-gage"], | ||
| "application/vnd.nokia.radio-preset": ["rpst"], | ||
| "application/vnd.nokia.radio-presets": ["rpss"], | ||
| "application/vnd.novadigm.edm": ["edm"], | ||
| "application/vnd.novadigm.edx": ["edx"], | ||
| "application/vnd.novadigm.ext": ["ext"], | ||
| "application/vnd.oasis.opendocument.chart": ["odc"], | ||
| "application/vnd.oasis.opendocument.chart-template": ["otc"], | ||
| "application/vnd.oasis.opendocument.database": ["odb"], | ||
| "application/vnd.oasis.opendocument.formula": ["odf"], | ||
| "application/vnd.oasis.opendocument.formula-template": ["odft"], | ||
| "application/vnd.oasis.opendocument.graphics": ["odg"], | ||
| "application/vnd.oasis.opendocument.graphics-template": ["otg"], | ||
| "application/vnd.oasis.opendocument.image": ["odi"], | ||
| "application/vnd.oasis.opendocument.image-template": ["oti"], | ||
| "application/vnd.oasis.opendocument.presentation": ["odp"], | ||
| "application/vnd.oasis.opendocument.presentation-template": ["otp"], | ||
| "application/vnd.oasis.opendocument.spreadsheet": ["ods"], | ||
| "application/vnd.oasis.opendocument.spreadsheet-template": ["ots"], | ||
| "application/vnd.oasis.opendocument.text": ["odt"], | ||
| "application/vnd.oasis.opendocument.text-master": ["odm"], | ||
| "application/vnd.oasis.opendocument.text-template": ["ott"], | ||
| "application/vnd.oasis.opendocument.text-web": ["oth"], | ||
| "application/vnd.olpc-sugar": ["xo"], | ||
| "application/vnd.oma.dd2+xml": ["dd2"], | ||
| "application/vnd.openblox.game+xml": ["obgx"], | ||
| "application/vnd.openofficeorg.extension": ["oxt"], | ||
| "application/vnd.openstreetmap.data+xml": ["osm"], | ||
| "application/vnd.openxmlformats-officedocument.presentationml.presentation": ["pptx"], | ||
| "application/vnd.openxmlformats-officedocument.presentationml.slide": ["sldx"], | ||
| "application/vnd.openxmlformats-officedocument.presentationml.slideshow": ["ppsx"], | ||
| "application/vnd.openxmlformats-officedocument.presentationml.template": ["potx"], | ||
| "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"], | ||
| "application/vnd.openxmlformats-officedocument.spreadsheetml.template": ["xltx"], | ||
| "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ["docx"], | ||
| "application/vnd.openxmlformats-officedocument.wordprocessingml.template": ["dotx"], | ||
| "application/vnd.osgeo.mapguide.package": ["mgp"], | ||
| "application/vnd.osgi.dp": ["dp"], | ||
| "application/vnd.osgi.subsystem": ["esa"], | ||
| "application/vnd.palm": [ | ||
| "pdb", | ||
| "pqa", | ||
| "oprc" | ||
| ], | ||
| "application/vnd.pawaafile": ["paw"], | ||
| "application/vnd.pg.format": ["str"], | ||
| "application/vnd.pg.osasli": ["ei6"], | ||
| "application/vnd.picsel": ["efif"], | ||
| "application/vnd.pmi.widget": ["wg"], | ||
| "application/vnd.pocketlearn": ["plf"], | ||
| "application/vnd.powerbuilder6": ["pbd"], | ||
| "application/vnd.previewsystems.box": ["box"], | ||
| "application/vnd.procrate.brushset": ["brushset"], | ||
| "application/vnd.procreate.brush": ["brush"], | ||
| "application/vnd.procreate.dream": ["drm"], | ||
| "application/vnd.proteus.magazine": ["mgz"], | ||
| "application/vnd.publishare-delta-tree": ["qps"], | ||
| "application/vnd.pvi.ptid1": ["ptid"], | ||
| "application/vnd.pwg-xhtml-print+xml": ["xhtm"], | ||
| "application/vnd.quark.quarkxpress": [ | ||
| "qxd", | ||
| "qxt", | ||
| "qwd", | ||
| "qwt", | ||
| "qxl", | ||
| "qxb" | ||
| ], | ||
| "application/vnd.rar": ["rar"], | ||
| "application/vnd.realvnc.bed": ["bed"], | ||
| "application/vnd.recordare.musicxml": ["mxl"], | ||
| "application/vnd.recordare.musicxml+xml": ["musicxml"], | ||
| "application/vnd.rig.cryptonote": ["cryptonote"], | ||
| "application/vnd.rim.cod": ["cod"], | ||
| "application/vnd.rn-realmedia": ["rm"], | ||
| "application/vnd.rn-realmedia-vbr": ["rmvb"], | ||
| "application/vnd.route66.link66+xml": ["link66"], | ||
| "application/vnd.sailingtracker.track": ["st"], | ||
| "application/vnd.seemail": ["see"], | ||
| "application/vnd.sema": ["sema"], | ||
| "application/vnd.semd": ["semd"], | ||
| "application/vnd.semf": ["semf"], | ||
| "application/vnd.shana.informed.formdata": ["ifm"], | ||
| "application/vnd.shana.informed.formtemplate": ["itp"], | ||
| "application/vnd.shana.informed.interchange": ["iif"], | ||
| "application/vnd.shana.informed.package": ["ipk"], | ||
| "application/vnd.simtech-mindmapper": ["twd", "twds"], | ||
| "application/vnd.smaf": ["mmf"], | ||
| "application/vnd.smart.teacher": ["teacher"], | ||
| "application/vnd.software602.filler.form+xml": ["fo"], | ||
| "application/vnd.solent.sdkm+xml": ["sdkm", "sdkd"], | ||
| "application/vnd.spotfire.dxp": ["dxp"], | ||
| "application/vnd.spotfire.sfs": ["sfs"], | ||
| "application/vnd.stardivision.calc": ["sdc"], | ||
| "application/vnd.stardivision.draw": ["sda"], | ||
| "application/vnd.stardivision.impress": ["sdd"], | ||
| "application/vnd.stardivision.math": ["smf"], | ||
| "application/vnd.stardivision.writer": ["sdw", "vor"], | ||
| "application/vnd.stardivision.writer-global": ["sgl"], | ||
| "application/vnd.stepmania.package": ["smzip"], | ||
| "application/vnd.stepmania.stepchart": ["sm"], | ||
| "application/vnd.sun.wadl+xml": ["wadl"], | ||
| "application/vnd.sun.xml.calc": ["sxc"], | ||
| "application/vnd.sun.xml.calc.template": ["stc"], | ||
| "application/vnd.sun.xml.draw": ["sxd"], | ||
| "application/vnd.sun.xml.draw.template": ["std"], | ||
| "application/vnd.sun.xml.impress": ["sxi"], | ||
| "application/vnd.sun.xml.impress.template": ["sti"], | ||
| "application/vnd.sun.xml.math": ["sxm"], | ||
| "application/vnd.sun.xml.writer": ["sxw"], | ||
| "application/vnd.sun.xml.writer.global": ["sxg"], | ||
| "application/vnd.sun.xml.writer.template": ["stw"], | ||
| "application/vnd.sus-calendar": ["sus", "susp"], | ||
| "application/vnd.svd": ["svd"], | ||
| "application/vnd.symbian.install": ["sis", "sisx"], | ||
| "application/vnd.syncml+xml": ["xsm"], | ||
| "application/vnd.syncml.dm+wbxml": ["bdm"], | ||
| "application/vnd.syncml.dm+xml": ["xdm"], | ||
| "application/vnd.syncml.dmddf+xml": ["ddf"], | ||
| "application/vnd.tao.intent-module-archive": ["tao"], | ||
| "application/vnd.tcpdump.pcap": [ | ||
| "pcap", | ||
| "cap", | ||
| "dmp" | ||
| ], | ||
| "application/vnd.tmobile-livetv": ["tmo"], | ||
| "application/vnd.trid.tpt": ["tpt"], | ||
| "application/vnd.triscape.mxs": ["mxs"], | ||
| "application/vnd.trueapp": ["tra"], | ||
| "application/vnd.ufdl": ["ufd", "ufdl"], | ||
| "application/vnd.uiq.theme": ["utz"], | ||
| "application/vnd.umajin": ["umj"], | ||
| "application/vnd.unity": ["unityweb"], | ||
| "application/vnd.uoml+xml": ["uoml", "uo"], | ||
| "application/vnd.vcx": ["vcx"], | ||
| "application/vnd.visio": [ | ||
| "vsd", | ||
| "vst", | ||
| "vss", | ||
| "vsw", | ||
| "vsdx", | ||
| "vtx" | ||
| ], | ||
| "application/vnd.visionary": ["vis"], | ||
| "application/vnd.vsf": ["vsf"], | ||
| "application/vnd.wap.wbxml": ["wbxml"], | ||
| "application/vnd.wap.wmlc": ["wmlc"], | ||
| "application/vnd.wap.wmlscriptc": ["wmlsc"], | ||
| "application/vnd.webturbo": ["wtb"], | ||
| "application/vnd.wolfram.player": ["nbp"], | ||
| "application/vnd.wordperfect": ["wpd"], | ||
| "application/vnd.wqd": ["wqd"], | ||
| "application/vnd.wt.stf": ["stf"], | ||
| "application/vnd.xara": ["xar"], | ||
| "application/vnd.xfdl": ["xfdl"], | ||
| "application/vnd.yamaha.hv-dic": ["hvd"], | ||
| "application/vnd.yamaha.hv-script": ["hvs"], | ||
| "application/vnd.yamaha.hv-voice": ["hvp"], | ||
| "application/vnd.yamaha.openscoreformat": ["osf"], | ||
| "application/vnd.yamaha.openscoreformat.osfpvg+xml": ["osfpvg"], | ||
| "application/vnd.yamaha.smaf-audio": ["saf"], | ||
| "application/vnd.yamaha.smaf-phrase": ["spf"], | ||
| "application/vnd.yellowriver-custom-menu": ["cmp"], | ||
| "application/vnd.zul": ["zir", "zirz"], | ||
| "application/vnd.zzazz.deck+xml": ["zaz"], | ||
| "application/x-7z-compressed": ["7z"], | ||
| "application/x-abiword": ["abw"], | ||
| "application/x-ace-compressed": ["ace"], | ||
| "application/x-apple-diskimage": ["*dmg"], | ||
| "application/x-arj": ["arj"], | ||
| "application/x-authorware-bin": [ | ||
| "aab", | ||
| "x32", | ||
| "u32", | ||
| "vox" | ||
| ], | ||
| "application/x-authorware-map": ["aam"], | ||
| "application/x-authorware-seg": ["aas"], | ||
| "application/x-bcpio": ["bcpio"], | ||
| "application/x-bdoc": ["*bdoc"], | ||
| "application/x-bittorrent": ["torrent"], | ||
| "application/x-blender": ["blend"], | ||
| "application/x-blorb": ["blb", "blorb"], | ||
| "application/x-bzip": ["bz"], | ||
| "application/x-bzip2": ["bz2", "boz"], | ||
| "application/x-cbr": [ | ||
| "cbr", | ||
| "cba", | ||
| "cbt", | ||
| "cbz", | ||
| "cb7" | ||
| ], | ||
| "application/x-cdlink": ["vcd"], | ||
| "application/x-cfs-compressed": ["cfs"], | ||
| "application/x-chat": ["chat"], | ||
| "application/x-chess-pgn": ["pgn"], | ||
| "application/x-chrome-extension": ["crx"], | ||
| "application/x-cocoa": ["cco"], | ||
| "application/x-compressed": ["*rar"], | ||
| "application/x-conference": ["nsc"], | ||
| "application/x-cpio": ["cpio"], | ||
| "application/x-csh": ["csh"], | ||
| "application/x-debian-package": ["*deb", "udeb"], | ||
| "application/x-dgc-compressed": ["dgc"], | ||
| "application/x-director": [ | ||
| "dir", | ||
| "dcr", | ||
| "dxr", | ||
| "cst", | ||
| "cct", | ||
| "cxt", | ||
| "w3d", | ||
| "fgd", | ||
| "swa" | ||
| ], | ||
| "application/x-doom": ["wad"], | ||
| "application/x-dtbncx+xml": ["ncx"], | ||
| "application/x-dtbook+xml": ["dtb"], | ||
| "application/x-dtbresource+xml": ["res"], | ||
| "application/x-dvi": ["dvi"], | ||
| "application/x-envoy": ["evy"], | ||
| "application/x-eva": ["eva"], | ||
| "application/x-font-bdf": ["bdf"], | ||
| "application/x-font-ghostscript": ["gsf"], | ||
| "application/x-font-linux-psf": ["psf"], | ||
| "application/x-font-pcf": ["pcf"], | ||
| "application/x-font-snf": ["snf"], | ||
| "application/x-font-type1": [ | ||
| "pfa", | ||
| "pfb", | ||
| "pfm", | ||
| "afm" | ||
| ], | ||
| "application/x-freearc": ["arc"], | ||
| "application/x-futuresplash": ["spl"], | ||
| "application/x-gca-compressed": ["gca"], | ||
| "application/x-glulx": ["ulx"], | ||
| "application/x-gnumeric": ["gnumeric"], | ||
| "application/x-gramps-xml": ["gramps"], | ||
| "application/x-gtar": ["gtar"], | ||
| "application/x-hdf": ["hdf"], | ||
| "application/x-httpd-php": ["php"], | ||
| "application/x-install-instructions": ["install"], | ||
| "application/x-ipynb+json": ["ipynb"], | ||
| "application/x-iso9660-image": ["*iso"], | ||
| "application/x-iwork-keynote-sffkey": ["*key"], | ||
| "application/x-iwork-numbers-sffnumbers": ["*numbers"], | ||
| "application/x-iwork-pages-sffpages": ["*pages"], | ||
| "application/x-java-archive-diff": ["jardiff"], | ||
| "application/x-java-jnlp-file": ["jnlp"], | ||
| "application/x-keepass2": ["kdbx"], | ||
| "application/x-latex": ["latex"], | ||
| "application/x-lua-bytecode": ["luac"], | ||
| "application/x-lzh-compressed": ["lzh", "lha"], | ||
| "application/x-makeself": ["run"], | ||
| "application/x-mie": ["mie"], | ||
| "application/x-mobipocket-ebook": ["*prc", "mobi"], | ||
| "application/x-ms-application": ["application"], | ||
| "application/x-ms-shortcut": ["lnk"], | ||
| "application/x-ms-wmd": ["wmd"], | ||
| "application/x-ms-wmz": ["wmz"], | ||
| "application/x-ms-xbap": ["xbap"], | ||
| "application/x-msaccess": ["mdb"], | ||
| "application/x-msbinder": ["obd"], | ||
| "application/x-mscardfile": ["crd"], | ||
| "application/x-msclip": ["clp"], | ||
| "application/x-msdos-program": ["*exe"], | ||
| "application/x-msdownload": [ | ||
| "*exe", | ||
| "*dll", | ||
| "com", | ||
| "bat", | ||
| "*msi" | ||
| ], | ||
| "application/x-msmediaview": [ | ||
| "mvb", | ||
| "m13", | ||
| "m14" | ||
| ], | ||
| "application/x-msmetafile": [ | ||
| "*wmf", | ||
| "*wmz", | ||
| "*emf", | ||
| "emz" | ||
| ], | ||
| "application/x-msmoney": ["mny"], | ||
| "application/x-mspublisher": ["pub"], | ||
| "application/x-msschedule": ["scd"], | ||
| "application/x-msterminal": ["trm"], | ||
| "application/x-mswrite": ["wri"], | ||
| "application/x-netcdf": ["nc", "cdf"], | ||
| "application/x-ns-proxy-autoconfig": ["pac"], | ||
| "application/x-nzb": ["nzb"], | ||
| "application/x-perl": ["pl", "pm"], | ||
| "application/x-pilot": ["*prc", "*pdb"], | ||
| "application/x-pkcs12": ["p12", "pfx"], | ||
| "application/x-pkcs7-certificates": ["p7b", "spc"], | ||
| "application/x-pkcs7-certreqresp": ["p7r"], | ||
| "application/x-rar-compressed": ["*rar"], | ||
| "application/x-redhat-package-manager": ["rpm"], | ||
| "application/x-research-info-systems": ["ris"], | ||
| "application/x-sea": ["sea"], | ||
| "application/x-sh": ["sh"], | ||
| "application/x-shar": ["shar"], | ||
| "application/x-shockwave-flash": ["swf"], | ||
| "application/x-silverlight-app": ["xap"], | ||
| "application/x-sql": ["*sql"], | ||
| "application/x-stuffit": ["sit"], | ||
| "application/x-stuffitx": ["sitx"], | ||
| "application/x-subrip": ["srt"], | ||
| "application/x-sv4cpio": ["sv4cpio"], | ||
| "application/x-sv4crc": ["sv4crc"], | ||
| "application/x-t3vm-image": ["t3"], | ||
| "application/x-tads": ["gam"], | ||
| "application/x-tar": ["tar"], | ||
| "application/x-tcl": ["tcl", "tk"], | ||
| "application/x-tex": ["tex"], | ||
| "application/x-tex-tfm": ["tfm"], | ||
| "application/x-texinfo": ["texinfo", "texi"], | ||
| "application/x-tgif": ["*obj"], | ||
| "application/x-ustar": ["ustar"], | ||
| "application/x-virtualbox-hdd": ["hdd"], | ||
| "application/x-virtualbox-ova": ["ova"], | ||
| "application/x-virtualbox-ovf": ["ovf"], | ||
| "application/x-virtualbox-vbox": ["vbox"], | ||
| "application/x-virtualbox-vbox-extpack": ["vbox-extpack"], | ||
| "application/x-virtualbox-vdi": ["vdi"], | ||
| "application/x-virtualbox-vhd": ["vhd"], | ||
| "application/x-virtualbox-vmdk": ["vmdk"], | ||
| "application/x-wais-source": ["src"], | ||
| "application/x-web-app-manifest+json": ["webapp"], | ||
| "application/x-x509-ca-cert": [ | ||
| "der", | ||
| "crt", | ||
| "pem" | ||
| ], | ||
| "application/x-xfig": ["fig"], | ||
| "application/x-xliff+xml": ["*xlf"], | ||
| "application/x-xpinstall": ["xpi"], | ||
| "application/x-xz": ["xz"], | ||
| "application/x-zip-compressed": ["*zip"], | ||
| "application/x-zmachine": [ | ||
| "z1", | ||
| "z2", | ||
| "z3", | ||
| "z4", | ||
| "z5", | ||
| "z6", | ||
| "z7", | ||
| "z8" | ||
| ], | ||
| "audio/vnd.dece.audio": ["uva", "uvva"], | ||
| "audio/vnd.digital-winds": ["eol"], | ||
| "audio/vnd.dra": ["dra"], | ||
| "audio/vnd.dts": ["dts"], | ||
| "audio/vnd.dts.hd": ["dtshd"], | ||
| "audio/vnd.lucent.voice": ["lvp"], | ||
| "audio/vnd.ms-playready.media.pya": ["pya"], | ||
| "audio/vnd.nuera.ecelp4800": ["ecelp4800"], | ||
| "audio/vnd.nuera.ecelp7470": ["ecelp7470"], | ||
| "audio/vnd.nuera.ecelp9600": ["ecelp9600"], | ||
| "audio/vnd.rip": ["rip"], | ||
| "audio/x-aac": ["*aac"], | ||
| "audio/x-aiff": [ | ||
| "aif", | ||
| "aiff", | ||
| "aifc" | ||
| ], | ||
| "audio/x-caf": ["caf"], | ||
| "audio/x-flac": ["flac"], | ||
| "audio/x-m4a": ["*m4a"], | ||
| "audio/x-matroska": ["mka"], | ||
| "audio/x-mpegurl": ["m3u"], | ||
| "audio/x-ms-wax": ["wax"], | ||
| "audio/x-ms-wma": ["wma"], | ||
| "audio/x-pn-realaudio": ["ram", "ra"], | ||
| "audio/x-pn-realaudio-plugin": ["rmp"], | ||
| "audio/x-realaudio": ["*ra"], | ||
| "audio/x-wav": ["*wav"], | ||
| "chemical/x-cdx": ["cdx"], | ||
| "chemical/x-cif": ["cif"], | ||
| "chemical/x-cmdf": ["cmdf"], | ||
| "chemical/x-cml": ["cml"], | ||
| "chemical/x-csml": ["csml"], | ||
| "chemical/x-xyz": ["xyz"], | ||
| "image/prs.btif": ["btif", "btf"], | ||
| "image/prs.pti": ["pti"], | ||
| "image/vnd.adobe.photoshop": ["psd"], | ||
| "image/vnd.airzip.accelerator.azv": ["azv"], | ||
| "image/vnd.blockfact.facti": ["facti"], | ||
| "image/vnd.dece.graphic": [ | ||
| "uvi", | ||
| "uvvi", | ||
| "uvg", | ||
| "uvvg" | ||
| ], | ||
| "image/vnd.djvu": ["djvu", "djv"], | ||
| "image/vnd.dvb.subtitle": ["*sub"], | ||
| "image/vnd.dwg": ["dwg"], | ||
| "image/vnd.dxf": ["dxf"], | ||
| "image/vnd.fastbidsheet": ["fbs"], | ||
| "image/vnd.fpx": ["fpx"], | ||
| "image/vnd.fst": ["fst"], | ||
| "image/vnd.fujixerox.edmics-mmr": ["mmr"], | ||
| "image/vnd.fujixerox.edmics-rlc": ["rlc"], | ||
| "image/vnd.microsoft.icon": ["ico"], | ||
| "image/vnd.ms-dds": ["dds"], | ||
| "image/vnd.ms-modi": ["mdi"], | ||
| "image/vnd.ms-photo": ["wdp"], | ||
| "image/vnd.net-fpx": ["npx"], | ||
| "image/vnd.pco.b16": ["b16"], | ||
| "image/vnd.tencent.tap": ["tap"], | ||
| "image/vnd.valve.source.texture": ["vtf"], | ||
| "image/vnd.wap.wbmp": ["wbmp"], | ||
| "image/vnd.xiff": ["xif"], | ||
| "image/vnd.zbrush.pcx": ["pcx"], | ||
| "image/x-3ds": ["3ds"], | ||
| "image/x-adobe-dng": ["dng"], | ||
| "image/x-cmu-raster": ["ras"], | ||
| "image/x-cmx": ["cmx"], | ||
| "image/x-freehand": [ | ||
| "fh", | ||
| "fhc", | ||
| "fh4", | ||
| "fh5", | ||
| "fh7" | ||
| ], | ||
| "image/x-icon": ["*ico"], | ||
| "image/x-jng": ["jng"], | ||
| "image/x-mrsid-image": ["sid"], | ||
| "image/x-ms-bmp": ["*bmp"], | ||
| "image/x-pcx": ["*pcx"], | ||
| "image/x-pict": ["pic", "pct"], | ||
| "image/x-portable-anymap": ["pnm"], | ||
| "image/x-portable-bitmap": ["pbm"], | ||
| "image/x-portable-graymap": ["pgm"], | ||
| "image/x-portable-pixmap": ["ppm"], | ||
| "image/x-rgb": ["rgb"], | ||
| "image/x-tga": ["tga"], | ||
| "image/x-xbitmap": ["xbm"], | ||
| "image/x-xpixmap": ["xpm"], | ||
| "image/x-xwindowdump": ["xwd"], | ||
| "message/vnd.wfa.wsc": ["wsc"], | ||
| "model/vnd.bary": ["bary"], | ||
| "model/vnd.cld": ["cld"], | ||
| "model/vnd.collada+xml": ["dae"], | ||
| "model/vnd.dwf": ["dwf"], | ||
| "model/vnd.gdl": ["gdl"], | ||
| "model/vnd.gtw": ["gtw"], | ||
| "model/vnd.mts": ["*mts"], | ||
| "model/vnd.opengex": ["ogex"], | ||
| "model/vnd.parasolid.transmit.binary": ["x_b"], | ||
| "model/vnd.parasolid.transmit.text": ["x_t"], | ||
| "model/vnd.pytha.pyox": ["pyo", "pyox"], | ||
| "model/vnd.sap.vds": ["vds"], | ||
| "model/vnd.usda": ["usda"], | ||
| "model/vnd.usdz+zip": ["usdz"], | ||
| "model/vnd.valve.source.compiled-map": ["bsp"], | ||
| "model/vnd.vtu": ["vtu"], | ||
| "text/prs.lines.tag": ["dsc"], | ||
| "text/vnd.curl": ["curl"], | ||
| "text/vnd.curl.dcurl": ["dcurl"], | ||
| "text/vnd.curl.mcurl": ["mcurl"], | ||
| "text/vnd.curl.scurl": ["scurl"], | ||
| "text/vnd.dvb.subtitle": ["sub"], | ||
| "text/vnd.familysearch.gedcom": ["ged"], | ||
| "text/vnd.fly": ["fly"], | ||
| "text/vnd.fmi.flexstor": ["flx"], | ||
| "text/vnd.graphviz": ["gv"], | ||
| "text/vnd.in3d.3dml": ["3dml"], | ||
| "text/vnd.in3d.spot": ["spot"], | ||
| "text/vnd.sun.j2me.app-descriptor": ["jad"], | ||
| "text/vnd.wap.wml": ["wml"], | ||
| "text/vnd.wap.wmlscript": ["wmls"], | ||
| "text/x-asm": ["s", "asm"], | ||
| "text/x-c": [ | ||
| "c", | ||
| "cc", | ||
| "cxx", | ||
| "cpp", | ||
| "h", | ||
| "hh", | ||
| "dic" | ||
| ], | ||
| "text/x-component": ["htc"], | ||
| "text/x-fortran": [ | ||
| "f", | ||
| "for", | ||
| "f77", | ||
| "f90" | ||
| ], | ||
| "text/x-handlebars-template": ["hbs"], | ||
| "text/x-java-source": ["java"], | ||
| "text/x-lua": ["lua"], | ||
| "text/x-markdown": ["mkd"], | ||
| "text/x-nfo": ["nfo"], | ||
| "text/x-opml": ["opml"], | ||
| "text/x-org": ["*org"], | ||
| "text/x-pascal": ["p", "pas"], | ||
| "text/x-processing": ["pde"], | ||
| "text/x-sass": ["sass"], | ||
| "text/x-scss": ["scss"], | ||
| "text/x-setext": ["etx"], | ||
| "text/x-sfv": ["sfv"], | ||
| "text/x-suse-ymp": ["ymp"], | ||
| "text/x-uuencode": ["uu"], | ||
| "text/x-vcalendar": ["vcs"], | ||
| "text/x-vcard": ["vcf"], | ||
| "video/vnd.dece.hd": ["uvh", "uvvh"], | ||
| "video/vnd.dece.mobile": ["uvm", "uvvm"], | ||
| "video/vnd.dece.pd": ["uvp", "uvvp"], | ||
| "video/vnd.dece.sd": ["uvs", "uvvs"], | ||
| "video/vnd.dece.video": ["uvv", "uvvv"], | ||
| "video/vnd.dvb.file": ["dvb"], | ||
| "video/vnd.fvt": ["fvt"], | ||
| "video/vnd.mpegurl": ["mxu", "m4u"], | ||
| "video/vnd.ms-playready.media.pyv": ["pyv"], | ||
| "video/vnd.uvvu.mp4": ["uvu", "uvvu"], | ||
| "video/vnd.vivo": ["viv"], | ||
| "video/x-f4v": ["f4v"], | ||
| "video/x-fli": ["fli"], | ||
| "video/x-flv": ["flv"], | ||
| "video/x-m4v": ["m4v"], | ||
| "video/x-matroska": [ | ||
| "mkv", | ||
| "mk3d", | ||
| "mks" | ||
| ], | ||
| "video/x-mng": ["mng"], | ||
| "video/x-ms-asf": ["asf", "asx"], | ||
| "video/x-ms-vob": ["vob"], | ||
| "video/x-ms-wm": ["wm"], | ||
| "video/x-ms-wmv": ["wmv"], | ||
| "video/x-ms-wmx": ["wmx"], | ||
| "video/x-ms-wvx": ["wvx"], | ||
| "video/x-msvideo": ["avi"], | ||
| "video/x-sgi-movie": ["movie"], | ||
| "video/x-smv": ["smv"], | ||
| "x-conference/x-cooltalk": ["ice"] | ||
| }; | ||
| Object.freeze(types$1); | ||
| var other_default = types$1; | ||
| //#endregion | ||
| //#region node_modules/.pnpm/mime@4.1.0/node_modules/mime/dist/types/standard.js | ||
| const types = { | ||
| "application/andrew-inset": ["ez"], | ||
| "application/appinstaller": ["appinstaller"], | ||
| "application/applixware": ["aw"], | ||
| "application/appx": ["appx"], | ||
| "application/appxbundle": ["appxbundle"], | ||
| "application/atom+xml": ["atom"], | ||
| "application/atomcat+xml": ["atomcat"], | ||
| "application/atomdeleted+xml": ["atomdeleted"], | ||
| "application/atomsvc+xml": ["atomsvc"], | ||
| "application/atsc-dwd+xml": ["dwd"], | ||
| "application/atsc-held+xml": ["held"], | ||
| "application/atsc-rsat+xml": ["rsat"], | ||
| "application/automationml-aml+xml": ["aml"], | ||
| "application/automationml-amlx+zip": ["amlx"], | ||
| "application/bdoc": ["bdoc"], | ||
| "application/calendar+xml": ["xcs"], | ||
| "application/ccxml+xml": ["ccxml"], | ||
| "application/cdfx+xml": ["cdfx"], | ||
| "application/cdmi-capability": ["cdmia"], | ||
| "application/cdmi-container": ["cdmic"], | ||
| "application/cdmi-domain": ["cdmid"], | ||
| "application/cdmi-object": ["cdmio"], | ||
| "application/cdmi-queue": ["cdmiq"], | ||
| "application/cpl+xml": ["cpl"], | ||
| "application/cu-seeme": ["cu"], | ||
| "application/cwl": ["cwl"], | ||
| "application/dash+xml": ["mpd"], | ||
| "application/dash-patch+xml": ["mpp"], | ||
| "application/davmount+xml": ["davmount"], | ||
| "application/dicom": ["dcm"], | ||
| "application/docbook+xml": ["dbk"], | ||
| "application/dssc+der": ["dssc"], | ||
| "application/dssc+xml": ["xdssc"], | ||
| "application/ecmascript": ["ecma"], | ||
| "application/emma+xml": ["emma"], | ||
| "application/emotionml+xml": ["emotionml"], | ||
| "application/epub+zip": ["epub"], | ||
| "application/exi": ["exi"], | ||
| "application/express": ["exp"], | ||
| "application/fdf": ["fdf"], | ||
| "application/fdt+xml": ["fdt"], | ||
| "application/font-tdpfr": ["pfr"], | ||
| "application/geo+json": ["geojson"], | ||
| "application/gml+xml": ["gml"], | ||
| "application/gpx+xml": ["gpx"], | ||
| "application/gxf": ["gxf"], | ||
| "application/gzip": ["gz"], | ||
| "application/hjson": ["hjson"], | ||
| "application/hyperstudio": ["stk"], | ||
| "application/inkml+xml": ["ink", "inkml"], | ||
| "application/ipfix": ["ipfix"], | ||
| "application/its+xml": ["its"], | ||
| "application/java-archive": [ | ||
| "jar", | ||
| "war", | ||
| "ear" | ||
| ], | ||
| "application/java-serialized-object": ["ser"], | ||
| "application/java-vm": ["class"], | ||
| "application/javascript": ["*js"], | ||
| "application/json": ["json", "map"], | ||
| "application/json5": ["json5"], | ||
| "application/jsonml+json": ["jsonml"], | ||
| "application/ld+json": ["jsonld"], | ||
| "application/lgr+xml": ["lgr"], | ||
| "application/lost+xml": ["lostxml"], | ||
| "application/mac-binhex40": ["hqx"], | ||
| "application/mac-compactpro": ["cpt"], | ||
| "application/mads+xml": ["mads"], | ||
| "application/manifest+json": ["webmanifest"], | ||
| "application/marc": ["mrc"], | ||
| "application/marcxml+xml": ["mrcx"], | ||
| "application/mathematica": [ | ||
| "ma", | ||
| "nb", | ||
| "mb" | ||
| ], | ||
| "application/mathml+xml": ["mathml"], | ||
| "application/mbox": ["mbox"], | ||
| "application/media-policy-dataset+xml": ["mpf"], | ||
| "application/mediaservercontrol+xml": ["mscml"], | ||
| "application/metalink+xml": ["metalink"], | ||
| "application/metalink4+xml": ["meta4"], | ||
| "application/mets+xml": ["mets"], | ||
| "application/mmt-aei+xml": ["maei"], | ||
| "application/mmt-usd+xml": ["musd"], | ||
| "application/mods+xml": ["mods"], | ||
| "application/mp21": ["m21", "mp21"], | ||
| "application/mp4": [ | ||
| "*mp4", | ||
| "*mpg4", | ||
| "mp4s", | ||
| "m4p" | ||
| ], | ||
| "application/msix": ["msix"], | ||
| "application/msixbundle": ["msixbundle"], | ||
| "application/msword": ["doc", "dot"], | ||
| "application/mxf": ["mxf"], | ||
| "application/n-quads": ["nq"], | ||
| "application/n-triples": ["nt"], | ||
| "application/node": ["cjs"], | ||
| "application/octet-stream": [ | ||
| "bin", | ||
| "dms", | ||
| "lrf", | ||
| "mar", | ||
| "so", | ||
| "dist", | ||
| "distz", | ||
| "pkg", | ||
| "bpk", | ||
| "dump", | ||
| "elc", | ||
| "deploy", | ||
| "exe", | ||
| "dll", | ||
| "deb", | ||
| "dmg", | ||
| "iso", | ||
| "img", | ||
| "msi", | ||
| "msp", | ||
| "msm", | ||
| "buffer" | ||
| ], | ||
| "application/oda": ["oda"], | ||
| "application/oebps-package+xml": ["opf"], | ||
| "application/ogg": ["ogx"], | ||
| "application/omdoc+xml": ["omdoc"], | ||
| "application/onenote": [ | ||
| "onetoc", | ||
| "onetoc2", | ||
| "onetmp", | ||
| "onepkg", | ||
| "one", | ||
| "onea" | ||
| ], | ||
| "application/oxps": ["oxps"], | ||
| "application/p2p-overlay+xml": ["relo"], | ||
| "application/patch-ops-error+xml": ["xer"], | ||
| "application/pdf": ["pdf"], | ||
| "application/pgp-encrypted": ["pgp"], | ||
| "application/pgp-keys": ["asc"], | ||
| "application/pgp-signature": ["sig", "*asc"], | ||
| "application/pics-rules": ["prf"], | ||
| "application/pkcs10": ["p10"], | ||
| "application/pkcs7-mime": ["p7m", "p7c"], | ||
| "application/pkcs7-signature": ["p7s"], | ||
| "application/pkcs8": ["p8"], | ||
| "application/pkix-attr-cert": ["ac"], | ||
| "application/pkix-cert": ["cer"], | ||
| "application/pkix-crl": ["crl"], | ||
| "application/pkix-pkipath": ["pkipath"], | ||
| "application/pkixcmp": ["pki"], | ||
| "application/pls+xml": ["pls"], | ||
| "application/postscript": [ | ||
| "ai", | ||
| "eps", | ||
| "ps" | ||
| ], | ||
| "application/provenance+xml": ["provx"], | ||
| "application/pskc+xml": ["pskcxml"], | ||
| "application/raml+yaml": ["raml"], | ||
| "application/rdf+xml": ["rdf", "owl"], | ||
| "application/reginfo+xml": ["rif"], | ||
| "application/relax-ng-compact-syntax": ["rnc"], | ||
| "application/resource-lists+xml": ["rl"], | ||
| "application/resource-lists-diff+xml": ["rld"], | ||
| "application/rls-services+xml": ["rs"], | ||
| "application/route-apd+xml": ["rapd"], | ||
| "application/route-s-tsid+xml": ["sls"], | ||
| "application/route-usd+xml": ["rusd"], | ||
| "application/rpki-ghostbusters": ["gbr"], | ||
| "application/rpki-manifest": ["mft"], | ||
| "application/rpki-roa": ["roa"], | ||
| "application/rsd+xml": ["rsd"], | ||
| "application/rss+xml": ["rss"], | ||
| "application/rtf": ["rtf"], | ||
| "application/sbml+xml": ["sbml"], | ||
| "application/scvp-cv-request": ["scq"], | ||
| "application/scvp-cv-response": ["scs"], | ||
| "application/scvp-vp-request": ["spq"], | ||
| "application/scvp-vp-response": ["spp"], | ||
| "application/sdp": ["sdp"], | ||
| "application/senml+xml": ["senmlx"], | ||
| "application/sensml+xml": ["sensmlx"], | ||
| "application/set-payment-initiation": ["setpay"], | ||
| "application/set-registration-initiation": ["setreg"], | ||
| "application/shf+xml": ["shf"], | ||
| "application/sieve": ["siv", "sieve"], | ||
| "application/smil+xml": ["smi", "smil"], | ||
| "application/sparql-query": ["rq"], | ||
| "application/sparql-results+xml": ["srx"], | ||
| "application/sql": ["sql"], | ||
| "application/srgs": ["gram"], | ||
| "application/srgs+xml": ["grxml"], | ||
| "application/sru+xml": ["sru"], | ||
| "application/ssdl+xml": ["ssdl"], | ||
| "application/ssml+xml": ["ssml"], | ||
| "application/swid+xml": ["swidtag"], | ||
| "application/tei+xml": ["tei", "teicorpus"], | ||
| "application/thraud+xml": ["tfi"], | ||
| "application/timestamped-data": ["tsd"], | ||
| "application/toml": ["toml"], | ||
| "application/trig": ["trig"], | ||
| "application/ttml+xml": ["ttml"], | ||
| "application/ubjson": ["ubj"], | ||
| "application/urc-ressheet+xml": ["rsheet"], | ||
| "application/urc-targetdesc+xml": ["td"], | ||
| "application/voicexml+xml": ["vxml"], | ||
| "application/wasm": ["wasm"], | ||
| "application/watcherinfo+xml": ["wif"], | ||
| "application/widget": ["wgt"], | ||
| "application/winhlp": ["hlp"], | ||
| "application/wsdl+xml": ["wsdl"], | ||
| "application/wspolicy+xml": ["wspolicy"], | ||
| "application/xaml+xml": ["xaml"], | ||
| "application/xcap-att+xml": ["xav"], | ||
| "application/xcap-caps+xml": ["xca"], | ||
| "application/xcap-diff+xml": ["xdf"], | ||
| "application/xcap-el+xml": ["xel"], | ||
| "application/xcap-ns+xml": ["xns"], | ||
| "application/xenc+xml": ["xenc"], | ||
| "application/xfdf": ["xfdf"], | ||
| "application/xhtml+xml": ["xhtml", "xht"], | ||
| "application/xliff+xml": ["xlf"], | ||
| "application/xml": [ | ||
| "xml", | ||
| "xsl", | ||
| "xsd", | ||
| "rng" | ||
| ], | ||
| "application/xml-dtd": ["dtd"], | ||
| "application/xop+xml": ["xop"], | ||
| "application/xproc+xml": ["xpl"], | ||
| "application/xslt+xml": ["*xsl", "xslt"], | ||
| "application/xspf+xml": ["xspf"], | ||
| "application/xv+xml": [ | ||
| "mxml", | ||
| "xhvml", | ||
| "xvml", | ||
| "xvm" | ||
| ], | ||
| "application/yang": ["yang"], | ||
| "application/yin+xml": ["yin"], | ||
| "application/zip": ["zip"], | ||
| "application/zip+dotlottie": ["lottie"], | ||
| "audio/3gpp": ["*3gpp"], | ||
| "audio/aac": ["adts", "aac"], | ||
| "audio/adpcm": ["adp"], | ||
| "audio/amr": ["amr"], | ||
| "audio/basic": ["au", "snd"], | ||
| "audio/midi": [ | ||
| "mid", | ||
| "midi", | ||
| "kar", | ||
| "rmi" | ||
| ], | ||
| "audio/mobile-xmf": ["mxmf"], | ||
| "audio/mp3": ["*mp3"], | ||
| "audio/mp4": [ | ||
| "m4a", | ||
| "mp4a", | ||
| "m4b" | ||
| ], | ||
| "audio/mpeg": [ | ||
| "mpga", | ||
| "mp2", | ||
| "mp2a", | ||
| "mp3", | ||
| "m2a", | ||
| "m3a" | ||
| ], | ||
| "audio/ogg": [ | ||
| "oga", | ||
| "ogg", | ||
| "spx", | ||
| "opus" | ||
| ], | ||
| "audio/s3m": ["s3m"], | ||
| "audio/silk": ["sil"], | ||
| "audio/wav": ["wav"], | ||
| "audio/wave": ["*wav"], | ||
| "audio/webm": ["weba"], | ||
| "audio/xm": ["xm"], | ||
| "font/collection": ["ttc"], | ||
| "font/otf": ["otf"], | ||
| "font/ttf": ["ttf"], | ||
| "font/woff": ["woff"], | ||
| "font/woff2": ["woff2"], | ||
| "image/aces": ["exr"], | ||
| "image/apng": ["apng"], | ||
| "image/avci": ["avci"], | ||
| "image/avcs": ["avcs"], | ||
| "image/avif": ["avif"], | ||
| "image/bmp": ["bmp", "dib"], | ||
| "image/cgm": ["cgm"], | ||
| "image/dicom-rle": ["drle"], | ||
| "image/dpx": ["dpx"], | ||
| "image/emf": ["emf"], | ||
| "image/fits": ["fits"], | ||
| "image/g3fax": ["g3"], | ||
| "image/gif": ["gif"], | ||
| "image/heic": ["heic"], | ||
| "image/heic-sequence": ["heics"], | ||
| "image/heif": ["heif"], | ||
| "image/heif-sequence": ["heifs"], | ||
| "image/hej2k": ["hej2"], | ||
| "image/ief": ["ief"], | ||
| "image/jaii": ["jaii"], | ||
| "image/jais": ["jais"], | ||
| "image/jls": ["jls"], | ||
| "image/jp2": ["jp2", "jpg2"], | ||
| "image/jpeg": [ | ||
| "jpg", | ||
| "jpeg", | ||
| "jpe" | ||
| ], | ||
| "image/jph": ["jph"], | ||
| "image/jphc": ["jhc"], | ||
| "image/jpm": ["jpm", "jpgm"], | ||
| "image/jpx": ["jpx", "jpf"], | ||
| "image/jxl": ["jxl"], | ||
| "image/jxr": ["jxr"], | ||
| "image/jxra": ["jxra"], | ||
| "image/jxrs": ["jxrs"], | ||
| "image/jxs": ["jxs"], | ||
| "image/jxsc": ["jxsc"], | ||
| "image/jxsi": ["jxsi"], | ||
| "image/jxss": ["jxss"], | ||
| "image/ktx": ["ktx"], | ||
| "image/ktx2": ["ktx2"], | ||
| "image/pjpeg": ["jfif"], | ||
| "image/png": ["png"], | ||
| "image/sgi": ["sgi"], | ||
| "image/svg+xml": ["svg", "svgz"], | ||
| "image/t38": ["t38"], | ||
| "image/tiff": ["tif", "tiff"], | ||
| "image/tiff-fx": ["tfx"], | ||
| "image/webp": ["webp"], | ||
| "image/wmf": ["wmf"], | ||
| "message/disposition-notification": ["disposition-notification"], | ||
| "message/global": ["u8msg"], | ||
| "message/global-delivery-status": ["u8dsn"], | ||
| "message/global-disposition-notification": ["u8mdn"], | ||
| "message/global-headers": ["u8hdr"], | ||
| "message/rfc822": [ | ||
| "eml", | ||
| "mime", | ||
| "mht", | ||
| "mhtml" | ||
| ], | ||
| "model/3mf": ["3mf"], | ||
| "model/gltf+json": ["gltf"], | ||
| "model/gltf-binary": ["glb"], | ||
| "model/iges": ["igs", "iges"], | ||
| "model/jt": ["jt"], | ||
| "model/mesh": [ | ||
| "msh", | ||
| "mesh", | ||
| "silo" | ||
| ], | ||
| "model/mtl": ["mtl"], | ||
| "model/obj": ["obj"], | ||
| "model/prc": ["prc"], | ||
| "model/step": [ | ||
| "step", | ||
| "stp", | ||
| "stpnc", | ||
| "p21", | ||
| "210" | ||
| ], | ||
| "model/step+xml": ["stpx"], | ||
| "model/step+zip": ["stpz"], | ||
| "model/step-xml+zip": ["stpxz"], | ||
| "model/stl": ["stl"], | ||
| "model/u3d": ["u3d"], | ||
| "model/vrml": ["wrl", "vrml"], | ||
| "model/x3d+binary": ["*x3db", "x3dbz"], | ||
| "model/x3d+fastinfoset": ["x3db"], | ||
| "model/x3d+vrml": ["*x3dv", "x3dvz"], | ||
| "model/x3d+xml": ["x3d", "x3dz"], | ||
| "model/x3d-vrml": ["x3dv"], | ||
| "text/cache-manifest": ["appcache", "manifest"], | ||
| "text/calendar": ["ics", "ifb"], | ||
| "text/coffeescript": ["coffee", "litcoffee"], | ||
| "text/css": ["css"], | ||
| "text/csv": ["csv"], | ||
| "text/html": [ | ||
| "html", | ||
| "htm", | ||
| "shtml" | ||
| ], | ||
| "text/jade": ["jade"], | ||
| "text/javascript": ["js", "mjs"], | ||
| "text/jsx": ["jsx"], | ||
| "text/less": ["less"], | ||
| "text/markdown": ["md", "markdown"], | ||
| "text/mathml": ["mml"], | ||
| "text/mdx": ["mdx"], | ||
| "text/n3": ["n3"], | ||
| "text/plain": [ | ||
| "txt", | ||
| "text", | ||
| "conf", | ||
| "def", | ||
| "list", | ||
| "log", | ||
| "in", | ||
| "ini" | ||
| ], | ||
| "text/richtext": ["rtx"], | ||
| "text/rtf": ["*rtf"], | ||
| "text/sgml": ["sgml", "sgm"], | ||
| "text/shex": ["shex"], | ||
| "text/slim": ["slim", "slm"], | ||
| "text/spdx": ["spdx"], | ||
| "text/stylus": ["stylus", "styl"], | ||
| "text/tab-separated-values": ["tsv"], | ||
| "text/troff": [ | ||
| "t", | ||
| "tr", | ||
| "roff", | ||
| "man", | ||
| "me", | ||
| "ms" | ||
| ], | ||
| "text/turtle": ["ttl"], | ||
| "text/uri-list": [ | ||
| "uri", | ||
| "uris", | ||
| "urls" | ||
| ], | ||
| "text/vcard": ["vcard"], | ||
| "text/vtt": ["vtt"], | ||
| "text/wgsl": ["wgsl"], | ||
| "text/xml": ["*xml"], | ||
| "text/yaml": ["yaml", "yml"], | ||
| "video/3gpp": ["3gp", "3gpp"], | ||
| "video/3gpp2": ["3g2"], | ||
| "video/h261": ["h261"], | ||
| "video/h263": ["h263"], | ||
| "video/h264": ["h264"], | ||
| "video/iso.segment": ["m4s"], | ||
| "video/jpeg": ["jpgv"], | ||
| "video/jpm": ["*jpm", "*jpgm"], | ||
| "video/mj2": ["mj2", "mjp2"], | ||
| "video/mp2t": [ | ||
| "ts", | ||
| "m2t", | ||
| "m2ts", | ||
| "mts" | ||
| ], | ||
| "video/mp4": [ | ||
| "mp4", | ||
| "mp4v", | ||
| "mpg4" | ||
| ], | ||
| "video/mpeg": [ | ||
| "mpeg", | ||
| "mpg", | ||
| "mpe", | ||
| "m1v", | ||
| "m2v" | ||
| ], | ||
| "video/ogg": ["ogv"], | ||
| "video/quicktime": ["qt", "mov"], | ||
| "video/webm": ["webm"] | ||
| }; | ||
| Object.freeze(types); | ||
| var standard_default = types; | ||
| //#endregion | ||
| //#region node_modules/.pnpm/mime@4.1.0/node_modules/mime/dist/src/Mime.js | ||
| var __classPrivateFieldGet = void 0 && (void 0).__classPrivateFieldGet || function(receiver, state, kind, f) { | ||
| if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); | ||
| if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); | ||
| return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); | ||
| }; | ||
| var _Mime_extensionToType, _Mime_typeToExtension, _Mime_typeToExtensions; | ||
| var Mime = class { | ||
| constructor(...args) { | ||
| _Mime_extensionToType.set(this, /* @__PURE__ */ new Map()); | ||
| _Mime_typeToExtension.set(this, /* @__PURE__ */ new Map()); | ||
| _Mime_typeToExtensions.set(this, /* @__PURE__ */ new Map()); | ||
| for (const arg of args) this.define(arg); | ||
| } | ||
| define(typeMap, force = false) { | ||
| for (let [type, extensions] of Object.entries(typeMap)) { | ||
| type = type.toLowerCase(); | ||
| extensions = extensions.map((ext) => ext.toLowerCase()); | ||
| if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").has(type)) __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, /* @__PURE__ */ new Set()); | ||
| const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type); | ||
| let first = true; | ||
| for (let extension of extensions) { | ||
| const starred = extension.startsWith("*"); | ||
| extension = starred ? extension.slice(1) : extension; | ||
| allExtensions?.add(extension); | ||
| if (first) __classPrivateFieldGet(this, _Mime_typeToExtension, "f").set(type, extension); | ||
| first = false; | ||
| if (starred) continue; | ||
| const currentType = __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(extension); | ||
| if (currentType && currentType != type && !force) throw new Error(`"${type} -> ${extension}" conflicts with "${currentType} -> ${extension}". Pass \`force=true\` to override this definition.`); | ||
| __classPrivateFieldGet(this, _Mime_extensionToType, "f").set(extension, type); | ||
| } | ||
| } | ||
| return this; | ||
| } | ||
| getType(path) { | ||
| if (typeof path !== "string") return null; | ||
| const last = path.replace(/^.*[/\\]/s, "").toLowerCase(); | ||
| const ext = last.replace(/^.*\./s, "").toLowerCase(); | ||
| const hasPath = last.length < path.length; | ||
| if (!(ext.length < last.length - 1) && hasPath) return null; | ||
| return __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(ext) ?? null; | ||
| } | ||
| getExtension(type) { | ||
| if (typeof type !== "string") return null; | ||
| type = type?.split?.(";")[0]; | ||
| return (type && __classPrivateFieldGet(this, _Mime_typeToExtension, "f").get(type.trim().toLowerCase())) ?? null; | ||
| } | ||
| getAllExtensions(type) { | ||
| if (typeof type !== "string") return null; | ||
| return __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type.toLowerCase()) ?? null; | ||
| } | ||
| _freeze() { | ||
| this.define = () => { | ||
| throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances"); | ||
| }; | ||
| Object.freeze(this); | ||
| for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").values()) Object.freeze(extensions); | ||
| return this; | ||
| } | ||
| _getTestState() { | ||
| return { | ||
| types: __classPrivateFieldGet(this, _Mime_extensionToType, "f"), | ||
| extensions: __classPrivateFieldGet(this, _Mime_typeToExtension, "f") | ||
| }; | ||
| } | ||
| }; | ||
| _Mime_extensionToType = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtension = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtensions = /* @__PURE__ */ new WeakMap(); | ||
| var Mime_default = Mime; | ||
| //#endregion | ||
| //#region node_modules/.pnpm/mime@4.1.0/node_modules/mime/dist/src/index.js | ||
| var src_default = new Mime_default(standard_default, other_default)._freeze(); | ||
| //#endregion | ||
| export { src_default as t }; |
| import { n as __require, t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| import { i as require_node_fetch_native_DhEqb06g, r as require_node } from "./giget.mjs"; | ||
| //#region node_modules/.pnpm/node-fetch-native@1.6.7/node_modules/node-fetch-native/dist/chunks/multipart-parser.cjs | ||
| var require_multipart_parser = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/node-fetch-native@1.6.7/node_modules/node-fetch-native/dist/chunks/multipart-parser.cjs": ((exports) => { | ||
| var y = Object.defineProperty; | ||
| var c = (R, o) => y(R, "name", { | ||
| value: o, | ||
| configurable: !0 | ||
| }); | ||
| const node = require_node(); | ||
| __require("node:http"), __require("node:https"), __require("node:zlib"), __require("node:stream"), __require("node:buffer"), __require("node:util"), require_node_fetch_native_DhEqb06g(), __require("node:url"), __require("node:net"), __require("node:fs"), __require("node:path"); | ||
| let s = 0; | ||
| const S = { | ||
| START_BOUNDARY: s++, | ||
| HEADER_FIELD_START: s++, | ||
| HEADER_FIELD: s++, | ||
| HEADER_VALUE_START: s++, | ||
| HEADER_VALUE: s++, | ||
| HEADER_VALUE_ALMOST_DONE: s++, | ||
| HEADERS_ALMOST_DONE: s++, | ||
| PART_DATA_START: s++, | ||
| PART_DATA: s++, | ||
| END: s++ | ||
| }; | ||
| let f = 1; | ||
| const F = { | ||
| PART_BOUNDARY: f, | ||
| LAST_BOUNDARY: f *= 2 | ||
| }, LF = 10, CR = 13, SPACE = 32, HYPHEN = 45, COLON = 58, A = 97, Z = 122, lower = c((R) => R | 32, "lower"), noop = c(() => {}, "noop"), g = class g$1 { | ||
| constructor(o) { | ||
| this.index = 0, this.flags = 0, this.onHeaderEnd = noop, this.onHeaderField = noop, this.onHeadersEnd = noop, this.onHeaderValue = noop, this.onPartBegin = noop, this.onPartData = noop, this.onPartEnd = noop, this.boundaryChars = {}, o = `\r | ||
| --` + o; | ||
| const t = new Uint8Array(o.length); | ||
| for (let n = 0; n < o.length; n++) t[n] = o.charCodeAt(n), this.boundaryChars[t[n]] = !0; | ||
| this.boundary = t, this.lookbehind = new Uint8Array(this.boundary.length + 8), this.state = S.START_BOUNDARY; | ||
| } | ||
| write(o) { | ||
| let t = 0; | ||
| const n = o.length; | ||
| let E = this.index, { lookbehind: l, boundary: h, boundaryChars: H, index: e, state: a, flags: d } = this; | ||
| const b = this.boundary.length, m = b - 1, O = o.length; | ||
| let r, P; | ||
| const u = c((D) => { | ||
| this[D + "Mark"] = t; | ||
| }, "mark"), i = c((D) => { | ||
| delete this[D + "Mark"]; | ||
| }, "clear"), T = c((D, p, _, N) => { | ||
| (p === void 0 || p !== _) && this[D](N && N.subarray(p, _)); | ||
| }, "callback"), L = c((D, p) => { | ||
| const _ = D + "Mark"; | ||
| _ in this && (p ? (T(D, this[_], t, o), delete this[_]) : (T(D, this[_], o.length, o), this[_] = 0)); | ||
| }, "dataCallback"); | ||
| for (t = 0; t < n; t++) switch (r = o[t], a) { | ||
| case S.START_BOUNDARY: | ||
| if (e === h.length - 2) { | ||
| if (r === HYPHEN) d |= F.LAST_BOUNDARY; | ||
| else if (r !== CR) return; | ||
| e++; | ||
| break; | ||
| } else if (e - 1 === h.length - 2) { | ||
| if (d & F.LAST_BOUNDARY && r === HYPHEN) a = S.END, d = 0; | ||
| else if (!(d & F.LAST_BOUNDARY) && r === LF) e = 0, T("onPartBegin"), a = S.HEADER_FIELD_START; | ||
| else return; | ||
| break; | ||
| } | ||
| r !== h[e + 2] && (e = -2), r === h[e + 2] && e++; | ||
| break; | ||
| case S.HEADER_FIELD_START: a = S.HEADER_FIELD, u("onHeaderField"), e = 0; | ||
| case S.HEADER_FIELD: | ||
| if (r === CR) { | ||
| i("onHeaderField"), a = S.HEADERS_ALMOST_DONE; | ||
| break; | ||
| } | ||
| if (e++, r === HYPHEN) break; | ||
| if (r === COLON) { | ||
| if (e === 1) return; | ||
| L("onHeaderField", !0), a = S.HEADER_VALUE_START; | ||
| break; | ||
| } | ||
| if (P = lower(r), P < A || P > Z) return; | ||
| break; | ||
| case S.HEADER_VALUE_START: | ||
| if (r === SPACE) break; | ||
| u("onHeaderValue"), a = S.HEADER_VALUE; | ||
| case S.HEADER_VALUE: | ||
| r === CR && (L("onHeaderValue", !0), T("onHeaderEnd"), a = S.HEADER_VALUE_ALMOST_DONE); | ||
| break; | ||
| case S.HEADER_VALUE_ALMOST_DONE: | ||
| if (r !== LF) return; | ||
| a = S.HEADER_FIELD_START; | ||
| break; | ||
| case S.HEADERS_ALMOST_DONE: | ||
| if (r !== LF) return; | ||
| T("onHeadersEnd"), a = S.PART_DATA_START; | ||
| break; | ||
| case S.PART_DATA_START: a = S.PART_DATA, u("onPartData"); | ||
| case S.PART_DATA: | ||
| if (E = e, e === 0) { | ||
| for (t += m; t < O && !(o[t] in H);) t += b; | ||
| t -= m, r = o[t]; | ||
| } | ||
| if (e < h.length) h[e] === r ? (e === 0 && L("onPartData", !0), e++) : e = 0; | ||
| else if (e === h.length) e++, r === CR ? d |= F.PART_BOUNDARY : r === HYPHEN ? d |= F.LAST_BOUNDARY : e = 0; | ||
| else if (e - 1 === h.length) if (d & F.PART_BOUNDARY) { | ||
| if (e = 0, r === LF) { | ||
| d &= ~F.PART_BOUNDARY, T("onPartEnd"), T("onPartBegin"), a = S.HEADER_FIELD_START; | ||
| break; | ||
| } | ||
| } else d & F.LAST_BOUNDARY && r === HYPHEN ? (T("onPartEnd"), a = S.END, d = 0) : e = 0; | ||
| if (e > 0) l[e - 1] = r; | ||
| else if (E > 0) { | ||
| const D = new Uint8Array(l.buffer, l.byteOffset, l.byteLength); | ||
| T("onPartData", 0, E, D), E = 0, u("onPartData"), t--; | ||
| } | ||
| break; | ||
| case S.END: break; | ||
| default: throw new Error(`Unexpected state entered: ${a}`); | ||
| } | ||
| L("onHeaderField"), L("onHeaderValue"), L("onPartData"), this.index = e, this.state = a, this.flags = d; | ||
| } | ||
| end() { | ||
| if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) this.onPartEnd(); | ||
| else if (this.state !== S.END) throw new Error("MultipartParser.end(): stream ended unexpectedly"); | ||
| } | ||
| }; | ||
| c(g, "MultipartParser"); | ||
| let MultipartParser = g; | ||
| function _fileName(R) { | ||
| const o = R.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i); | ||
| if (!o) return; | ||
| const t = o[2] || o[3] || ""; | ||
| let n = t.slice(t.lastIndexOf("\\") + 1); | ||
| return n = n.replace(/%22/g, "\""), n = n.replace(/&#(\d{4});/g, (E, l) => String.fromCharCode(l)), n; | ||
| } | ||
| c(_fileName, "_fileName"); | ||
| async function toFormData(R, o) { | ||
| if (!/multipart/i.test(o)) throw new TypeError("Failed to fetch"); | ||
| const t = o.match(/boundary=(?:"([^"]+)"|([^;]+))/i); | ||
| if (!t) throw new TypeError("no or bad content-type header, no multipart boundary"); | ||
| const n = new MultipartParser(t[1] || t[2]); | ||
| let E, l, h, H, e, a; | ||
| const d = [], b = new node.FormData(), m = c((i) => { | ||
| h += u.decode(i, { stream: !0 }); | ||
| }, "onPartData"), O = c((i) => { | ||
| d.push(i); | ||
| }, "appendToFile"), r = c(() => { | ||
| const i = new node.File(d, a, { type: e }); | ||
| b.append(H, i); | ||
| }, "appendFileToFormData"), P = c(() => { | ||
| b.append(H, h); | ||
| }, "appendEntryToFormData"), u = new TextDecoder("utf-8"); | ||
| u.decode(), n.onPartBegin = function() { | ||
| n.onPartData = m, n.onPartEnd = P, E = "", l = "", h = "", H = "", e = "", a = null, d.length = 0; | ||
| }, n.onHeaderField = function(i) { | ||
| E += u.decode(i, { stream: !0 }); | ||
| }, n.onHeaderValue = function(i) { | ||
| l += u.decode(i, { stream: !0 }); | ||
| }, n.onHeaderEnd = function() { | ||
| if (l += u.decode(), E = E.toLowerCase(), E === "content-disposition") { | ||
| const i = l.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); | ||
| i && (H = i[2] || i[3] || ""), a = _fileName(l), a && (n.onPartData = O, n.onPartEnd = r); | ||
| } else E === "content-type" && (e = l); | ||
| l = "", E = ""; | ||
| }; | ||
| for await (const i of R) n.write(i); | ||
| return n.end(), b; | ||
| } | ||
| c(toFormData, "toFormData"), exports.toFormData = toFormData; | ||
| }) }); | ||
| //#endregion | ||
| export { require_multipart_parser as t }; |
| import { t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| //#region node_modules/.pnpm/path-parse@1.0.7/node_modules/path-parse/index.js | ||
| var require_path_parse = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/path-parse@1.0.7/node_modules/path-parse/index.js": ((exports, module) => { | ||
| var isWindows = process.platform === "win32"; | ||
| var splitWindowsRe = /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/; | ||
| var win32 = {}; | ||
| function win32SplitPath(filename) { | ||
| return splitWindowsRe.exec(filename).slice(1); | ||
| } | ||
| win32.parse = function(pathString) { | ||
| if (typeof pathString !== "string") throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString); | ||
| var allParts = win32SplitPath(pathString); | ||
| if (!allParts || allParts.length !== 5) throw new TypeError("Invalid path '" + pathString + "'"); | ||
| return { | ||
| root: allParts[1], | ||
| dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1), | ||
| base: allParts[2], | ||
| ext: allParts[4], | ||
| name: allParts[3] | ||
| }; | ||
| }; | ||
| var splitPathRe = /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/; | ||
| var posix = {}; | ||
| function posixSplitPath(filename) { | ||
| return splitPathRe.exec(filename).slice(1); | ||
| } | ||
| posix.parse = function(pathString) { | ||
| if (typeof pathString !== "string") throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString); | ||
| var allParts = posixSplitPath(pathString); | ||
| if (!allParts || allParts.length !== 5) throw new TypeError("Invalid path '" + pathString + "'"); | ||
| return { | ||
| root: allParts[1], | ||
| dir: allParts[0].slice(0, -1), | ||
| base: allParts[2], | ||
| ext: allParts[4], | ||
| name: allParts[3] | ||
| }; | ||
| }; | ||
| if (isWindows) module.exports = win32.parse; | ||
| else module.exports = posix.parse; | ||
| module.exports.posix = posix.parse; | ||
| module.exports.win32 = win32.parse; | ||
| }) }); | ||
| //#endregion | ||
| export { require_path_parse as t }; |
| import { E as normalizeWindowsPath, w as join } from "./c12.mjs"; | ||
| //#region node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/utils.mjs | ||
| const pathSeparators = /* @__PURE__ */ new Set([ | ||
| "/", | ||
| "\\", | ||
| void 0 | ||
| ]); | ||
| const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias"); | ||
| function normalizeAliases(_aliases) { | ||
| if (_aliases[normalizedAliasSymbol]) return _aliases; | ||
| const aliases = Object.fromEntries(Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b))); | ||
| for (const key in aliases) for (const alias in aliases) { | ||
| if (alias === key || key.startsWith(alias)) continue; | ||
| if (aliases[key]?.startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) aliases[key] = aliases[alias] + aliases[key].slice(alias.length); | ||
| } | ||
| Object.defineProperty(aliases, normalizedAliasSymbol, { | ||
| value: true, | ||
| enumerable: false | ||
| }); | ||
| return aliases; | ||
| } | ||
| function resolveAlias(path, aliases) { | ||
| const _path = normalizeWindowsPath(path); | ||
| aliases = normalizeAliases(aliases); | ||
| for (const [alias, to] of Object.entries(aliases)) { | ||
| if (!_path.startsWith(alias)) continue; | ||
| if (hasTrailingSlash(_path[(hasTrailingSlash(alias) ? alias.slice(0, -1) : alias).length])) return join(to, _path.slice(alias.length)); | ||
| } | ||
| return _path; | ||
| } | ||
| function _compareAliases(a, b) { | ||
| return b.split("/").length - a.split("/").length; | ||
| } | ||
| function hasTrailingSlash(path = "/") { | ||
| const lastChar = path[path.length - 1]; | ||
| return lastChar === "/" || lastChar === "\\"; | ||
| } | ||
| //#endregion | ||
| export { resolveAlias as t }; |
| import { t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| //#region node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js | ||
| var require_constants = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js": ((exports, module) => { | ||
| const WIN_SLASH = "\\\\/"; | ||
| const WIN_NO_SLASH = `[^${WIN_SLASH}]`; | ||
| /** | ||
| * Posix glob regex | ||
| */ | ||
| const DOT_LITERAL = "\\."; | ||
| const PLUS_LITERAL = "\\+"; | ||
| const QMARK_LITERAL = "\\?"; | ||
| const SLASH_LITERAL = "\\/"; | ||
| const ONE_CHAR = "(?=.)"; | ||
| const QMARK = "[^/]"; | ||
| const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; | ||
| const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; | ||
| const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; | ||
| const POSIX_CHARS = { | ||
| DOT_LITERAL, | ||
| PLUS_LITERAL, | ||
| QMARK_LITERAL, | ||
| SLASH_LITERAL, | ||
| ONE_CHAR, | ||
| QMARK, | ||
| END_ANCHOR, | ||
| DOTS_SLASH, | ||
| NO_DOT: `(?!${DOT_LITERAL})`, | ||
| NO_DOTS: `(?!${START_ANCHOR}${DOTS_SLASH})`, | ||
| NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`, | ||
| NO_DOTS_SLASH: `(?!${DOTS_SLASH})`, | ||
| QMARK_NO_DOT: `[^.${SLASH_LITERAL}]`, | ||
| STAR: `${QMARK}*?`, | ||
| START_ANCHOR, | ||
| SEP: "/" | ||
| }; | ||
| /** | ||
| * Windows glob regex | ||
| */ | ||
| const WINDOWS_CHARS = { | ||
| ...POSIX_CHARS, | ||
| SLASH_LITERAL: `[${WIN_SLASH}]`, | ||
| QMARK: WIN_NO_SLASH, | ||
| STAR: `${WIN_NO_SLASH}*?`, | ||
| DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, | ||
| NO_DOT: `(?!${DOT_LITERAL})`, | ||
| NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, | ||
| NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, | ||
| NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, | ||
| QMARK_NO_DOT: `[^.${WIN_SLASH}]`, | ||
| START_ANCHOR: `(?:^|[${WIN_SLASH}])`, | ||
| END_ANCHOR: `(?:[${WIN_SLASH}]|$)`, | ||
| SEP: "\\" | ||
| }; | ||
| /** | ||
| * POSIX Bracket Regex | ||
| */ | ||
| const POSIX_REGEX_SOURCE$1 = { | ||
| alnum: "a-zA-Z0-9", | ||
| alpha: "a-zA-Z", | ||
| ascii: "\\x00-\\x7F", | ||
| blank: " \\t", | ||
| cntrl: "\\x00-\\x1F\\x7F", | ||
| digit: "0-9", | ||
| graph: "\\x21-\\x7E", | ||
| lower: "a-z", | ||
| print: "\\x20-\\x7E ", | ||
| punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~", | ||
| space: " \\t\\r\\n\\v\\f", | ||
| upper: "A-Z", | ||
| word: "A-Za-z0-9_", | ||
| xdigit: "A-Fa-f0-9" | ||
| }; | ||
| module.exports = { | ||
| MAX_LENGTH: 1024 * 64, | ||
| POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, | ||
| REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, | ||
| REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, | ||
| REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, | ||
| REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, | ||
| REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, | ||
| REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, | ||
| REPLACEMENTS: { | ||
| __proto__: null, | ||
| "***": "*", | ||
| "**/**": "**", | ||
| "**/**/**": "**" | ||
| }, | ||
| CHAR_0: 48, | ||
| CHAR_9: 57, | ||
| CHAR_UPPERCASE_A: 65, | ||
| CHAR_LOWERCASE_A: 97, | ||
| CHAR_UPPERCASE_Z: 90, | ||
| CHAR_LOWERCASE_Z: 122, | ||
| CHAR_LEFT_PARENTHESES: 40, | ||
| CHAR_RIGHT_PARENTHESES: 41, | ||
| CHAR_ASTERISK: 42, | ||
| CHAR_AMPERSAND: 38, | ||
| CHAR_AT: 64, | ||
| CHAR_BACKWARD_SLASH: 92, | ||
| CHAR_CARRIAGE_RETURN: 13, | ||
| CHAR_CIRCUMFLEX_ACCENT: 94, | ||
| CHAR_COLON: 58, | ||
| CHAR_COMMA: 44, | ||
| CHAR_DOT: 46, | ||
| CHAR_DOUBLE_QUOTE: 34, | ||
| CHAR_EQUAL: 61, | ||
| CHAR_EXCLAMATION_MARK: 33, | ||
| CHAR_FORM_FEED: 12, | ||
| CHAR_FORWARD_SLASH: 47, | ||
| CHAR_GRAVE_ACCENT: 96, | ||
| CHAR_HASH: 35, | ||
| CHAR_HYPHEN_MINUS: 45, | ||
| CHAR_LEFT_ANGLE_BRACKET: 60, | ||
| CHAR_LEFT_CURLY_BRACE: 123, | ||
| CHAR_LEFT_SQUARE_BRACKET: 91, | ||
| CHAR_LINE_FEED: 10, | ||
| CHAR_NO_BREAK_SPACE: 160, | ||
| CHAR_PERCENT: 37, | ||
| CHAR_PLUS: 43, | ||
| CHAR_QUESTION_MARK: 63, | ||
| CHAR_RIGHT_ANGLE_BRACKET: 62, | ||
| CHAR_RIGHT_CURLY_BRACE: 125, | ||
| CHAR_RIGHT_SQUARE_BRACKET: 93, | ||
| CHAR_SEMICOLON: 59, | ||
| CHAR_SINGLE_QUOTE: 39, | ||
| CHAR_SPACE: 32, | ||
| CHAR_TAB: 9, | ||
| CHAR_UNDERSCORE: 95, | ||
| CHAR_VERTICAL_LINE: 124, | ||
| CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, | ||
| extglobChars(chars) { | ||
| return { | ||
| "!": { | ||
| type: "negate", | ||
| open: "(?:(?!(?:", | ||
| close: `))${chars.STAR})` | ||
| }, | ||
| "?": { | ||
| type: "qmark", | ||
| open: "(?:", | ||
| close: ")?" | ||
| }, | ||
| "+": { | ||
| type: "plus", | ||
| open: "(?:", | ||
| close: ")+" | ||
| }, | ||
| "*": { | ||
| type: "star", | ||
| open: "(?:", | ||
| close: ")*" | ||
| }, | ||
| "@": { | ||
| type: "at", | ||
| open: "(?:", | ||
| close: ")" | ||
| } | ||
| }; | ||
| }, | ||
| globChars(win32) { | ||
| return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; | ||
| } | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js | ||
| var require_utils = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js": ((exports) => { | ||
| const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants(); | ||
| exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val); | ||
| exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str); | ||
| exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str); | ||
| exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1"); | ||
| exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/"); | ||
| exports.isWindows = () => { | ||
| if (typeof navigator !== "undefined" && navigator.platform) { | ||
| const platform = navigator.platform.toLowerCase(); | ||
| return platform === "win32" || platform === "windows"; | ||
| } | ||
| if (typeof process !== "undefined" && process.platform) return process.platform === "win32"; | ||
| return false; | ||
| }; | ||
| exports.removeBackslashes = (str) => { | ||
| return str.replace(REGEX_REMOVE_BACKSLASH, (match) => { | ||
| return match === "\\" ? "" : match; | ||
| }); | ||
| }; | ||
| exports.escapeLast = (input, char, lastIdx) => { | ||
| const idx = input.lastIndexOf(char, lastIdx); | ||
| if (idx === -1) return input; | ||
| if (input[idx - 1] === "\\") return exports.escapeLast(input, char, idx - 1); | ||
| return `${input.slice(0, idx)}\\${input.slice(idx)}`; | ||
| }; | ||
| exports.removePrefix = (input, state = {}) => { | ||
| let output = input; | ||
| if (output.startsWith("./")) { | ||
| output = output.slice(2); | ||
| state.prefix = "./"; | ||
| } | ||
| return output; | ||
| }; | ||
| exports.wrapOutput = (input, state = {}, options = {}) => { | ||
| let output = `${options.contains ? "" : "^"}(?:${input})${options.contains ? "" : "$"}`; | ||
| if (state.negated === true) output = `(?:^(?!${output}).*$)`; | ||
| return output; | ||
| }; | ||
| exports.basename = (path, { windows } = {}) => { | ||
| const segs = path.split(windows ? /[\\/]/ : "/"); | ||
| const last = segs[segs.length - 1]; | ||
| if (last === "") return segs[segs.length - 2]; | ||
| return last; | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js | ||
| var require_scan = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js": ((exports, module) => { | ||
| const utils$3 = require_utils(); | ||
| const { CHAR_ASTERISK, CHAR_AT, CHAR_BACKWARD_SLASH, CHAR_COMMA, CHAR_DOT, CHAR_EXCLAMATION_MARK, CHAR_FORWARD_SLASH, CHAR_LEFT_CURLY_BRACE, CHAR_LEFT_PARENTHESES, CHAR_LEFT_SQUARE_BRACKET, CHAR_PLUS, CHAR_QUESTION_MARK, CHAR_RIGHT_CURLY_BRACE, CHAR_RIGHT_PARENTHESES, CHAR_RIGHT_SQUARE_BRACKET } = require_constants(); | ||
| const isPathSeparator = (code) => { | ||
| return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; | ||
| }; | ||
| const depth = (token) => { | ||
| if (token.isPrefix !== true) token.depth = token.isGlobstar ? Infinity : 1; | ||
| }; | ||
| /** | ||
| * Quickly scans a glob pattern and returns an object with a handful of | ||
| * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), | ||
| * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not | ||
| * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). | ||
| * | ||
| * ```js | ||
| * const pm = require('picomatch'); | ||
| * console.log(pm.scan('foo/bar/*.js')); | ||
| * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } | ||
| * ``` | ||
| * @param {String} `str` | ||
| * @param {Object} `options` | ||
| * @return {Object} Returns an object with tokens and regex source string. | ||
| * @api public | ||
| */ | ||
| const scan$1 = (input, options) => { | ||
| const opts = options || {}; | ||
| const length = input.length - 1; | ||
| const scanToEnd = opts.parts === true || opts.scanToEnd === true; | ||
| const slashes = []; | ||
| const tokens = []; | ||
| const parts = []; | ||
| let str = input; | ||
| let index = -1; | ||
| let start = 0; | ||
| let lastIndex = 0; | ||
| let isBrace = false; | ||
| let isBracket = false; | ||
| let isGlob = false; | ||
| let isExtglob = false; | ||
| let isGlobstar = false; | ||
| let braceEscaped = false; | ||
| let backslashes = false; | ||
| let negated = false; | ||
| let negatedExtglob = false; | ||
| let finished = false; | ||
| let braces = 0; | ||
| let prev; | ||
| let code; | ||
| let token = { | ||
| value: "", | ||
| depth: 0, | ||
| isGlob: false | ||
| }; | ||
| const eos = () => index >= length; | ||
| const peek = () => str.charCodeAt(index + 1); | ||
| const advance = () => { | ||
| prev = code; | ||
| return str.charCodeAt(++index); | ||
| }; | ||
| while (index < length) { | ||
| code = advance(); | ||
| let next; | ||
| if (code === CHAR_BACKWARD_SLASH) { | ||
| backslashes = token.backslashes = true; | ||
| code = advance(); | ||
| if (code === CHAR_LEFT_CURLY_BRACE) braceEscaped = true; | ||
| continue; | ||
| } | ||
| if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { | ||
| braces++; | ||
| while (eos() !== true && (code = advance())) { | ||
| if (code === CHAR_BACKWARD_SLASH) { | ||
| backslashes = token.backslashes = true; | ||
| advance(); | ||
| continue; | ||
| } | ||
| if (code === CHAR_LEFT_CURLY_BRACE) { | ||
| braces++; | ||
| continue; | ||
| } | ||
| if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { | ||
| isBrace = token.isBrace = true; | ||
| isGlob = token.isGlob = true; | ||
| finished = true; | ||
| if (scanToEnd === true) continue; | ||
| break; | ||
| } | ||
| if (braceEscaped !== true && code === CHAR_COMMA) { | ||
| isBrace = token.isBrace = true; | ||
| isGlob = token.isGlob = true; | ||
| finished = true; | ||
| if (scanToEnd === true) continue; | ||
| break; | ||
| } | ||
| if (code === CHAR_RIGHT_CURLY_BRACE) { | ||
| braces--; | ||
| if (braces === 0) { | ||
| braceEscaped = false; | ||
| isBrace = token.isBrace = true; | ||
| finished = true; | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| if (scanToEnd === true) continue; | ||
| break; | ||
| } | ||
| if (code === CHAR_FORWARD_SLASH) { | ||
| slashes.push(index); | ||
| tokens.push(token); | ||
| token = { | ||
| value: "", | ||
| depth: 0, | ||
| isGlob: false | ||
| }; | ||
| if (finished === true) continue; | ||
| if (prev === CHAR_DOT && index === start + 1) { | ||
| start += 2; | ||
| continue; | ||
| } | ||
| lastIndex = index + 1; | ||
| continue; | ||
| } | ||
| if (opts.noext !== true) { | ||
| if ((code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK) === true && peek() === CHAR_LEFT_PARENTHESES) { | ||
| isGlob = token.isGlob = true; | ||
| isExtglob = token.isExtglob = true; | ||
| finished = true; | ||
| if (code === CHAR_EXCLAMATION_MARK && index === start) negatedExtglob = true; | ||
| if (scanToEnd === true) { | ||
| while (eos() !== true && (code = advance())) { | ||
| if (code === CHAR_BACKWARD_SLASH) { | ||
| backslashes = token.backslashes = true; | ||
| code = advance(); | ||
| continue; | ||
| } | ||
| if (code === CHAR_RIGHT_PARENTHESES) { | ||
| isGlob = token.isGlob = true; | ||
| finished = true; | ||
| break; | ||
| } | ||
| } | ||
| continue; | ||
| } | ||
| break; | ||
| } | ||
| } | ||
| if (code === CHAR_ASTERISK) { | ||
| if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; | ||
| isGlob = token.isGlob = true; | ||
| finished = true; | ||
| if (scanToEnd === true) continue; | ||
| break; | ||
| } | ||
| if (code === CHAR_QUESTION_MARK) { | ||
| isGlob = token.isGlob = true; | ||
| finished = true; | ||
| if (scanToEnd === true) continue; | ||
| break; | ||
| } | ||
| if (code === CHAR_LEFT_SQUARE_BRACKET) { | ||
| while (eos() !== true && (next = advance())) { | ||
| if (next === CHAR_BACKWARD_SLASH) { | ||
| backslashes = token.backslashes = true; | ||
| advance(); | ||
| continue; | ||
| } | ||
| if (next === CHAR_RIGHT_SQUARE_BRACKET) { | ||
| isBracket = token.isBracket = true; | ||
| isGlob = token.isGlob = true; | ||
| finished = true; | ||
| break; | ||
| } | ||
| } | ||
| if (scanToEnd === true) continue; | ||
| break; | ||
| } | ||
| if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { | ||
| negated = token.negated = true; | ||
| start++; | ||
| continue; | ||
| } | ||
| if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { | ||
| isGlob = token.isGlob = true; | ||
| if (scanToEnd === true) { | ||
| while (eos() !== true && (code = advance())) { | ||
| if (code === CHAR_LEFT_PARENTHESES) { | ||
| backslashes = token.backslashes = true; | ||
| code = advance(); | ||
| continue; | ||
| } | ||
| if (code === CHAR_RIGHT_PARENTHESES) { | ||
| finished = true; | ||
| break; | ||
| } | ||
| } | ||
| continue; | ||
| } | ||
| break; | ||
| } | ||
| if (isGlob === true) { | ||
| finished = true; | ||
| if (scanToEnd === true) continue; | ||
| break; | ||
| } | ||
| } | ||
| if (opts.noext === true) { | ||
| isExtglob = false; | ||
| isGlob = false; | ||
| } | ||
| let base = str; | ||
| let prefix = ""; | ||
| let glob = ""; | ||
| if (start > 0) { | ||
| prefix = str.slice(0, start); | ||
| str = str.slice(start); | ||
| lastIndex -= start; | ||
| } | ||
| if (base && isGlob === true && lastIndex > 0) { | ||
| base = str.slice(0, lastIndex); | ||
| glob = str.slice(lastIndex); | ||
| } else if (isGlob === true) { | ||
| base = ""; | ||
| glob = str; | ||
| } else base = str; | ||
| if (base && base !== "" && base !== "/" && base !== str) { | ||
| if (isPathSeparator(base.charCodeAt(base.length - 1))) base = base.slice(0, -1); | ||
| } | ||
| if (opts.unescape === true) { | ||
| if (glob) glob = utils$3.removeBackslashes(glob); | ||
| if (base && backslashes === true) base = utils$3.removeBackslashes(base); | ||
| } | ||
| const state = { | ||
| prefix, | ||
| input, | ||
| start, | ||
| base, | ||
| glob, | ||
| isBrace, | ||
| isBracket, | ||
| isGlob, | ||
| isExtglob, | ||
| isGlobstar, | ||
| negated, | ||
| negatedExtglob | ||
| }; | ||
| if (opts.tokens === true) { | ||
| state.maxDepth = 0; | ||
| if (!isPathSeparator(code)) tokens.push(token); | ||
| state.tokens = tokens; | ||
| } | ||
| if (opts.parts === true || opts.tokens === true) { | ||
| let prevIndex; | ||
| for (let idx = 0; idx < slashes.length; idx++) { | ||
| const n = prevIndex ? prevIndex + 1 : start; | ||
| const i = slashes[idx]; | ||
| const value = input.slice(n, i); | ||
| if (opts.tokens) { | ||
| if (idx === 0 && start !== 0) { | ||
| tokens[idx].isPrefix = true; | ||
| tokens[idx].value = prefix; | ||
| } else tokens[idx].value = value; | ||
| depth(tokens[idx]); | ||
| state.maxDepth += tokens[idx].depth; | ||
| } | ||
| if (idx !== 0 || value !== "") parts.push(value); | ||
| prevIndex = i; | ||
| } | ||
| if (prevIndex && prevIndex + 1 < input.length) { | ||
| const value = input.slice(prevIndex + 1); | ||
| parts.push(value); | ||
| if (opts.tokens) { | ||
| tokens[tokens.length - 1].value = value; | ||
| depth(tokens[tokens.length - 1]); | ||
| state.maxDepth += tokens[tokens.length - 1].depth; | ||
| } | ||
| } | ||
| state.slashes = slashes; | ||
| state.parts = parts; | ||
| } | ||
| return state; | ||
| }; | ||
| module.exports = scan$1; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js | ||
| var require_parse = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js": ((exports, module) => { | ||
| const constants$1 = require_constants(); | ||
| const utils$2 = require_utils(); | ||
| /** | ||
| * Constants | ||
| */ | ||
| const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$1; | ||
| /** | ||
| * Helpers | ||
| */ | ||
| const expandRange = (args, options) => { | ||
| if (typeof options.expandRange === "function") return options.expandRange(...args, options); | ||
| args.sort(); | ||
| const value = `[${args.join("-")}]`; | ||
| try { | ||
| new RegExp(value); | ||
| } catch (ex) { | ||
| return args.map((v) => utils$2.escapeRegex(v)).join(".."); | ||
| } | ||
| return value; | ||
| }; | ||
| /** | ||
| * Create the message for a syntax error | ||
| */ | ||
| const syntaxError = (type, char) => { | ||
| return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; | ||
| }; | ||
| /** | ||
| * Parse the given input string. | ||
| * @param {String} input | ||
| * @param {Object} options | ||
| * @return {Object} | ||
| */ | ||
| const parse$1 = (input, options) => { | ||
| if (typeof input !== "string") throw new TypeError("Expected a string"); | ||
| input = REPLACEMENTS[input] || input; | ||
| const opts = { ...options }; | ||
| const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; | ||
| let len = input.length; | ||
| if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); | ||
| const bos = { | ||
| type: "bos", | ||
| value: "", | ||
| output: opts.prepend || "" | ||
| }; | ||
| const tokens = [bos]; | ||
| const capture = opts.capture ? "" : "?:"; | ||
| const PLATFORM_CHARS = constants$1.globChars(opts.windows); | ||
| const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS); | ||
| const { DOT_LITERAL: DOT_LITERAL$1, PLUS_LITERAL: PLUS_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK: QMARK$1, QMARK_NO_DOT, STAR, START_ANCHOR: START_ANCHOR$1 } = PLATFORM_CHARS; | ||
| const globstar = (opts$1) => { | ||
| return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`; | ||
| }; | ||
| const nodot = opts.dot ? "" : NO_DOT; | ||
| const qmarkNoDot = opts.dot ? QMARK$1 : QMARK_NO_DOT; | ||
| let star = opts.bash === true ? globstar(opts) : STAR; | ||
| if (opts.capture) star = `(${star})`; | ||
| if (typeof opts.noext === "boolean") opts.noextglob = opts.noext; | ||
| const state = { | ||
| input, | ||
| index: -1, | ||
| start: 0, | ||
| dot: opts.dot === true, | ||
| consumed: "", | ||
| output: "", | ||
| prefix: "", | ||
| backtrack: false, | ||
| negated: false, | ||
| brackets: 0, | ||
| braces: 0, | ||
| parens: 0, | ||
| quotes: 0, | ||
| globstar: false, | ||
| tokens | ||
| }; | ||
| input = utils$2.removePrefix(input, state); | ||
| len = input.length; | ||
| const extglobs = []; | ||
| const braces = []; | ||
| const stack = []; | ||
| let prev = bos; | ||
| let value; | ||
| /** | ||
| * Tokenizing helpers | ||
| */ | ||
| const eos = () => state.index === len - 1; | ||
| const peek = state.peek = (n = 1) => input[state.index + n]; | ||
| const advance = state.advance = () => input[++state.index] || ""; | ||
| const remaining = () => input.slice(state.index + 1); | ||
| const consume = (value$1 = "", num = 0) => { | ||
| state.consumed += value$1; | ||
| state.index += num; | ||
| }; | ||
| const append = (token) => { | ||
| state.output += token.output != null ? token.output : token.value; | ||
| consume(token.value); | ||
| }; | ||
| const negate = () => { | ||
| let count = 1; | ||
| while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) { | ||
| advance(); | ||
| state.start++; | ||
| count++; | ||
| } | ||
| if (count % 2 === 0) return false; | ||
| state.negated = true; | ||
| state.start++; | ||
| return true; | ||
| }; | ||
| const increment = (type) => { | ||
| state[type]++; | ||
| stack.push(type); | ||
| }; | ||
| const decrement = (type) => { | ||
| state[type]--; | ||
| stack.pop(); | ||
| }; | ||
| /** | ||
| * Push tokens onto the tokens array. This helper speeds up | ||
| * tokenizing by 1) helping us avoid backtracking as much as possible, | ||
| * and 2) helping us avoid creating extra tokens when consecutive | ||
| * characters are plain text. This improves performance and simplifies | ||
| * lookbehinds. | ||
| */ | ||
| const push = (tok) => { | ||
| if (prev.type === "globstar") { | ||
| const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace"); | ||
| const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren"); | ||
| if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) { | ||
| state.output = state.output.slice(0, -prev.output.length); | ||
| prev.type = "star"; | ||
| prev.value = "*"; | ||
| prev.output = star; | ||
| state.output += prev.output; | ||
| } | ||
| } | ||
| if (extglobs.length && tok.type !== "paren") extglobs[extglobs.length - 1].inner += tok.value; | ||
| if (tok.value || tok.output) append(tok); | ||
| if (prev && prev.type === "text" && tok.type === "text") { | ||
| prev.output = (prev.output || prev.value) + tok.value; | ||
| prev.value += tok.value; | ||
| return; | ||
| } | ||
| tok.prev = prev; | ||
| tokens.push(tok); | ||
| prev = tok; | ||
| }; | ||
| const extglobOpen = (type, value$1) => { | ||
| const token = { | ||
| ...EXTGLOB_CHARS[value$1], | ||
| conditions: 1, | ||
| inner: "" | ||
| }; | ||
| token.prev = prev; | ||
| token.parens = state.parens; | ||
| token.output = state.output; | ||
| const output = (opts.capture ? "(" : "") + token.open; | ||
| increment("parens"); | ||
| push({ | ||
| type, | ||
| value: value$1, | ||
| output: state.output ? "" : ONE_CHAR$1 | ||
| }); | ||
| push({ | ||
| type: "paren", | ||
| extglob: true, | ||
| value: advance(), | ||
| output | ||
| }); | ||
| extglobs.push(token); | ||
| }; | ||
| const extglobClose = (token) => { | ||
| let output = token.close + (opts.capture ? ")" : ""); | ||
| let rest; | ||
| if (token.type === "negate") { | ||
| let extglobStar = star; | ||
| if (token.inner && token.inner.length > 1 && token.inner.includes("/")) extglobStar = globstar(opts); | ||
| if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) output = token.close = `)$))${extglobStar}`; | ||
| if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) output = token.close = `)${parse$1(rest, { | ||
| ...options, | ||
| fastpaths: false | ||
| }).output})${extglobStar})`; | ||
| if (token.prev.type === "bos") state.negatedExtglob = true; | ||
| } | ||
| push({ | ||
| type: "paren", | ||
| extglob: true, | ||
| value, | ||
| output | ||
| }); | ||
| decrement("parens"); | ||
| }; | ||
| /** | ||
| * Fast paths | ||
| */ | ||
| if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { | ||
| let backslashes = false; | ||
| let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { | ||
| if (first === "\\") { | ||
| backslashes = true; | ||
| return m; | ||
| } | ||
| if (first === "?") { | ||
| if (esc) return esc + first + (rest ? QMARK$1.repeat(rest.length) : ""); | ||
| if (index === 0) return qmarkNoDot + (rest ? QMARK$1.repeat(rest.length) : ""); | ||
| return QMARK$1.repeat(chars.length); | ||
| } | ||
| if (first === ".") return DOT_LITERAL$1.repeat(chars.length); | ||
| if (first === "*") { | ||
| if (esc) return esc + first + (rest ? star : ""); | ||
| return star; | ||
| } | ||
| return esc ? m : `\\${m}`; | ||
| }); | ||
| if (backslashes === true) if (opts.unescape === true) output = output.replace(/\\/g, ""); | ||
| else output = output.replace(/\\+/g, (m) => { | ||
| return m.length % 2 === 0 ? "\\\\" : m ? "\\" : ""; | ||
| }); | ||
| if (output === input && opts.contains === true) { | ||
| state.output = input; | ||
| return state; | ||
| } | ||
| state.output = utils$2.wrapOutput(output, state, options); | ||
| return state; | ||
| } | ||
| /** | ||
| * Tokenize input until we reach end-of-string | ||
| */ | ||
| while (!eos()) { | ||
| value = advance(); | ||
| if (value === "\0") continue; | ||
| /** | ||
| * Escaped characters | ||
| */ | ||
| if (value === "\\") { | ||
| const next = peek(); | ||
| if (next === "/" && opts.bash !== true) continue; | ||
| if (next === "." || next === ";") continue; | ||
| if (!next) { | ||
| value += "\\"; | ||
| push({ | ||
| type: "text", | ||
| value | ||
| }); | ||
| continue; | ||
| } | ||
| const match = /^\\+/.exec(remaining()); | ||
| let slashes = 0; | ||
| if (match && match[0].length > 2) { | ||
| slashes = match[0].length; | ||
| state.index += slashes; | ||
| if (slashes % 2 !== 0) value += "\\"; | ||
| } | ||
| if (opts.unescape === true) value = advance(); | ||
| else value += advance(); | ||
| if (state.brackets === 0) { | ||
| push({ | ||
| type: "text", | ||
| value | ||
| }); | ||
| continue; | ||
| } | ||
| } | ||
| /** | ||
| * If we're inside a regex character class, continue | ||
| * until we reach the closing bracket. | ||
| */ | ||
| if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) { | ||
| if (opts.posix !== false && value === ":") { | ||
| const inner = prev.value.slice(1); | ||
| if (inner.includes("[")) { | ||
| prev.posix = true; | ||
| if (inner.includes(":")) { | ||
| const idx = prev.value.lastIndexOf("["); | ||
| const pre = prev.value.slice(0, idx); | ||
| const posix = POSIX_REGEX_SOURCE[prev.value.slice(idx + 2)]; | ||
| if (posix) { | ||
| prev.value = pre + posix; | ||
| state.backtrack = true; | ||
| advance(); | ||
| if (!bos.output && tokens.indexOf(prev) === 1) bos.output = ONE_CHAR$1; | ||
| continue; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") value = `\\${value}`; | ||
| if (value === "]" && (prev.value === "[" || prev.value === "[^")) value = `\\${value}`; | ||
| if (opts.posix === true && value === "!" && prev.value === "[") value = "^"; | ||
| prev.value += value; | ||
| append({ value }); | ||
| continue; | ||
| } | ||
| /** | ||
| * If we're inside a quoted string, continue | ||
| * until we reach the closing double quote. | ||
| */ | ||
| if (state.quotes === 1 && value !== "\"") { | ||
| value = utils$2.escapeRegex(value); | ||
| prev.value += value; | ||
| append({ value }); | ||
| continue; | ||
| } | ||
| /** | ||
| * Double quotes | ||
| */ | ||
| if (value === "\"") { | ||
| state.quotes = state.quotes === 1 ? 0 : 1; | ||
| if (opts.keepQuotes === true) push({ | ||
| type: "text", | ||
| value | ||
| }); | ||
| continue; | ||
| } | ||
| /** | ||
| * Parentheses | ||
| */ | ||
| if (value === "(") { | ||
| increment("parens"); | ||
| push({ | ||
| type: "paren", | ||
| value | ||
| }); | ||
| continue; | ||
| } | ||
| if (value === ")") { | ||
| if (state.parens === 0 && opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "(")); | ||
| const extglob = extglobs[extglobs.length - 1]; | ||
| if (extglob && state.parens === extglob.parens + 1) { | ||
| extglobClose(extglobs.pop()); | ||
| continue; | ||
| } | ||
| push({ | ||
| type: "paren", | ||
| value, | ||
| output: state.parens ? ")" : "\\)" | ||
| }); | ||
| decrement("parens"); | ||
| continue; | ||
| } | ||
| /** | ||
| * Square brackets | ||
| */ | ||
| if (value === "[") { | ||
| if (opts.nobracket === true || !remaining().includes("]")) { | ||
| if (opts.nobracket !== true && opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]")); | ||
| value = `\\${value}`; | ||
| } else increment("brackets"); | ||
| push({ | ||
| type: "bracket", | ||
| value | ||
| }); | ||
| continue; | ||
| } | ||
| if (value === "]") { | ||
| if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) { | ||
| push({ | ||
| type: "text", | ||
| value, | ||
| output: `\\${value}` | ||
| }); | ||
| continue; | ||
| } | ||
| if (state.brackets === 0) { | ||
| if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "[")); | ||
| push({ | ||
| type: "text", | ||
| value, | ||
| output: `\\${value}` | ||
| }); | ||
| continue; | ||
| } | ||
| decrement("brackets"); | ||
| const prevValue = prev.value.slice(1); | ||
| if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) value = `/${value}`; | ||
| prev.value += value; | ||
| append({ value }); | ||
| if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) continue; | ||
| const escaped = utils$2.escapeRegex(prev.value); | ||
| state.output = state.output.slice(0, -prev.value.length); | ||
| if (opts.literalBrackets === true) { | ||
| state.output += escaped; | ||
| prev.value = escaped; | ||
| continue; | ||
| } | ||
| prev.value = `(${capture}${escaped}|${prev.value})`; | ||
| state.output += prev.value; | ||
| continue; | ||
| } | ||
| /** | ||
| * Braces | ||
| */ | ||
| if (value === "{" && opts.nobrace !== true) { | ||
| increment("braces"); | ||
| const open = { | ||
| type: "brace", | ||
| value, | ||
| output: "(", | ||
| outputIndex: state.output.length, | ||
| tokensIndex: state.tokens.length | ||
| }; | ||
| braces.push(open); | ||
| push(open); | ||
| continue; | ||
| } | ||
| if (value === "}") { | ||
| const brace = braces[braces.length - 1]; | ||
| if (opts.nobrace === true || !brace) { | ||
| push({ | ||
| type: "text", | ||
| value, | ||
| output: value | ||
| }); | ||
| continue; | ||
| } | ||
| let output = ")"; | ||
| if (brace.dots === true) { | ||
| const arr = tokens.slice(); | ||
| const range = []; | ||
| for (let i = arr.length - 1; i >= 0; i--) { | ||
| tokens.pop(); | ||
| if (arr[i].type === "brace") break; | ||
| if (arr[i].type !== "dots") range.unshift(arr[i].value); | ||
| } | ||
| output = expandRange(range, opts); | ||
| state.backtrack = true; | ||
| } | ||
| if (brace.comma !== true && brace.dots !== true) { | ||
| const out = state.output.slice(0, brace.outputIndex); | ||
| const toks = state.tokens.slice(brace.tokensIndex); | ||
| brace.value = brace.output = "\\{"; | ||
| value = output = "\\}"; | ||
| state.output = out; | ||
| for (const t of toks) state.output += t.output || t.value; | ||
| } | ||
| push({ | ||
| type: "brace", | ||
| value, | ||
| output | ||
| }); | ||
| decrement("braces"); | ||
| braces.pop(); | ||
| continue; | ||
| } | ||
| /** | ||
| * Pipes | ||
| */ | ||
| if (value === "|") { | ||
| if (extglobs.length > 0) extglobs[extglobs.length - 1].conditions++; | ||
| push({ | ||
| type: "text", | ||
| value | ||
| }); | ||
| continue; | ||
| } | ||
| /** | ||
| * Commas | ||
| */ | ||
| if (value === ",") { | ||
| let output = value; | ||
| const brace = braces[braces.length - 1]; | ||
| if (brace && stack[stack.length - 1] === "braces") { | ||
| brace.comma = true; | ||
| output = "|"; | ||
| } | ||
| push({ | ||
| type: "comma", | ||
| value, | ||
| output | ||
| }); | ||
| continue; | ||
| } | ||
| /** | ||
| * Slashes | ||
| */ | ||
| if (value === "/") { | ||
| if (prev.type === "dot" && state.index === state.start + 1) { | ||
| state.start = state.index + 1; | ||
| state.consumed = ""; | ||
| state.output = ""; | ||
| tokens.pop(); | ||
| prev = bos; | ||
| continue; | ||
| } | ||
| push({ | ||
| type: "slash", | ||
| value, | ||
| output: SLASH_LITERAL$1 | ||
| }); | ||
| continue; | ||
| } | ||
| /** | ||
| * Dots | ||
| */ | ||
| if (value === ".") { | ||
| if (state.braces > 0 && prev.type === "dot") { | ||
| if (prev.value === ".") prev.output = DOT_LITERAL$1; | ||
| const brace = braces[braces.length - 1]; | ||
| prev.type = "dots"; | ||
| prev.output += value; | ||
| prev.value += value; | ||
| brace.dots = true; | ||
| continue; | ||
| } | ||
| if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") { | ||
| push({ | ||
| type: "text", | ||
| value, | ||
| output: DOT_LITERAL$1 | ||
| }); | ||
| continue; | ||
| } | ||
| push({ | ||
| type: "dot", | ||
| value, | ||
| output: DOT_LITERAL$1 | ||
| }); | ||
| continue; | ||
| } | ||
| /** | ||
| * Question marks | ||
| */ | ||
| if (value === "?") { | ||
| if (!(prev && prev.value === "(") && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { | ||
| extglobOpen("qmark", value); | ||
| continue; | ||
| } | ||
| if (prev && prev.type === "paren") { | ||
| const next = peek(); | ||
| let output = value; | ||
| if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) output = `\\${value}`; | ||
| push({ | ||
| type: "text", | ||
| value, | ||
| output | ||
| }); | ||
| continue; | ||
| } | ||
| if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) { | ||
| push({ | ||
| type: "qmark", | ||
| value, | ||
| output: QMARK_NO_DOT | ||
| }); | ||
| continue; | ||
| } | ||
| push({ | ||
| type: "qmark", | ||
| value, | ||
| output: QMARK$1 | ||
| }); | ||
| continue; | ||
| } | ||
| /** | ||
| * Exclamation | ||
| */ | ||
| if (value === "!") { | ||
| if (opts.noextglob !== true && peek() === "(") { | ||
| if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) { | ||
| extglobOpen("negate", value); | ||
| continue; | ||
| } | ||
| } | ||
| if (opts.nonegate !== true && state.index === 0) { | ||
| negate(); | ||
| continue; | ||
| } | ||
| } | ||
| /** | ||
| * Plus | ||
| */ | ||
| if (value === "+") { | ||
| if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { | ||
| extglobOpen("plus", value); | ||
| continue; | ||
| } | ||
| if (prev && prev.value === "(" || opts.regex === false) { | ||
| push({ | ||
| type: "plus", | ||
| value, | ||
| output: PLUS_LITERAL$1 | ||
| }); | ||
| continue; | ||
| } | ||
| if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) { | ||
| push({ | ||
| type: "plus", | ||
| value | ||
| }); | ||
| continue; | ||
| } | ||
| push({ | ||
| type: "plus", | ||
| value: PLUS_LITERAL$1 | ||
| }); | ||
| continue; | ||
| } | ||
| /** | ||
| * Plain text | ||
| */ | ||
| if (value === "@") { | ||
| if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { | ||
| push({ | ||
| type: "at", | ||
| extglob: true, | ||
| value, | ||
| output: "" | ||
| }); | ||
| continue; | ||
| } | ||
| push({ | ||
| type: "text", | ||
| value | ||
| }); | ||
| continue; | ||
| } | ||
| /** | ||
| * Plain text | ||
| */ | ||
| if (value !== "*") { | ||
| if (value === "$" || value === "^") value = `\\${value}`; | ||
| const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); | ||
| if (match) { | ||
| value += match[0]; | ||
| state.index += match[0].length; | ||
| } | ||
| push({ | ||
| type: "text", | ||
| value | ||
| }); | ||
| continue; | ||
| } | ||
| /** | ||
| * Stars | ||
| */ | ||
| if (prev && (prev.type === "globstar" || prev.star === true)) { | ||
| prev.type = "star"; | ||
| prev.star = true; | ||
| prev.value += value; | ||
| prev.output = star; | ||
| state.backtrack = true; | ||
| state.globstar = true; | ||
| consume(value); | ||
| continue; | ||
| } | ||
| let rest = remaining(); | ||
| if (opts.noextglob !== true && /^\([^?]/.test(rest)) { | ||
| extglobOpen("star", value); | ||
| continue; | ||
| } | ||
| if (prev.type === "star") { | ||
| if (opts.noglobstar === true) { | ||
| consume(value); | ||
| continue; | ||
| } | ||
| const prior = prev.prev; | ||
| const before = prior.prev; | ||
| const isStart = prior.type === "slash" || prior.type === "bos"; | ||
| const afterStar = before && (before.type === "star" || before.type === "globstar"); | ||
| if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) { | ||
| push({ | ||
| type: "star", | ||
| value, | ||
| output: "" | ||
| }); | ||
| continue; | ||
| } | ||
| const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace"); | ||
| const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren"); | ||
| if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) { | ||
| push({ | ||
| type: "star", | ||
| value, | ||
| output: "" | ||
| }); | ||
| continue; | ||
| } | ||
| while (rest.slice(0, 3) === "/**") { | ||
| const after = input[state.index + 4]; | ||
| if (after && after !== "/") break; | ||
| rest = rest.slice(3); | ||
| consume("/**", 3); | ||
| } | ||
| if (prior.type === "bos" && eos()) { | ||
| prev.type = "globstar"; | ||
| prev.value += value; | ||
| prev.output = globstar(opts); | ||
| state.output = prev.output; | ||
| state.globstar = true; | ||
| consume(value); | ||
| continue; | ||
| } | ||
| if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) { | ||
| state.output = state.output.slice(0, -(prior.output + prev.output).length); | ||
| prior.output = `(?:${prior.output}`; | ||
| prev.type = "globstar"; | ||
| prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)"); | ||
| prev.value += value; | ||
| state.globstar = true; | ||
| state.output += prior.output + prev.output; | ||
| consume(value); | ||
| continue; | ||
| } | ||
| if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") { | ||
| const end = rest[1] !== void 0 ? "|$" : ""; | ||
| state.output = state.output.slice(0, -(prior.output + prev.output).length); | ||
| prior.output = `(?:${prior.output}`; | ||
| prev.type = "globstar"; | ||
| prev.output = `${globstar(opts)}${SLASH_LITERAL$1}|${SLASH_LITERAL$1}${end})`; | ||
| prev.value += value; | ||
| state.output += prior.output + prev.output; | ||
| state.globstar = true; | ||
| consume(value + advance()); | ||
| push({ | ||
| type: "slash", | ||
| value: "/", | ||
| output: "" | ||
| }); | ||
| continue; | ||
| } | ||
| if (prior.type === "bos" && rest[0] === "/") { | ||
| prev.type = "globstar"; | ||
| prev.value += value; | ||
| prev.output = `(?:^|${SLASH_LITERAL$1}|${globstar(opts)}${SLASH_LITERAL$1})`; | ||
| state.output = prev.output; | ||
| state.globstar = true; | ||
| consume(value + advance()); | ||
| push({ | ||
| type: "slash", | ||
| value: "/", | ||
| output: "" | ||
| }); | ||
| continue; | ||
| } | ||
| state.output = state.output.slice(0, -prev.output.length); | ||
| prev.type = "globstar"; | ||
| prev.output = globstar(opts); | ||
| prev.value += value; | ||
| state.output += prev.output; | ||
| state.globstar = true; | ||
| consume(value); | ||
| continue; | ||
| } | ||
| const token = { | ||
| type: "star", | ||
| value, | ||
| output: star | ||
| }; | ||
| if (opts.bash === true) { | ||
| token.output = ".*?"; | ||
| if (prev.type === "bos" || prev.type === "slash") token.output = nodot + token.output; | ||
| push(token); | ||
| continue; | ||
| } | ||
| if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) { | ||
| token.output = value; | ||
| push(token); | ||
| continue; | ||
| } | ||
| if (state.index === state.start || prev.type === "slash" || prev.type === "dot") { | ||
| if (prev.type === "dot") { | ||
| state.output += NO_DOT_SLASH; | ||
| prev.output += NO_DOT_SLASH; | ||
| } else if (opts.dot === true) { | ||
| state.output += NO_DOTS_SLASH; | ||
| prev.output += NO_DOTS_SLASH; | ||
| } else { | ||
| state.output += nodot; | ||
| prev.output += nodot; | ||
| } | ||
| if (peek() !== "*") { | ||
| state.output += ONE_CHAR$1; | ||
| prev.output += ONE_CHAR$1; | ||
| } | ||
| } | ||
| push(token); | ||
| } | ||
| while (state.brackets > 0) { | ||
| if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]")); | ||
| state.output = utils$2.escapeLast(state.output, "["); | ||
| decrement("brackets"); | ||
| } | ||
| while (state.parens > 0) { | ||
| if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")")); | ||
| state.output = utils$2.escapeLast(state.output, "("); | ||
| decrement("parens"); | ||
| } | ||
| while (state.braces > 0) { | ||
| if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}")); | ||
| state.output = utils$2.escapeLast(state.output, "{"); | ||
| decrement("braces"); | ||
| } | ||
| if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) push({ | ||
| type: "maybe_slash", | ||
| value: "", | ||
| output: `${SLASH_LITERAL$1}?` | ||
| }); | ||
| if (state.backtrack === true) { | ||
| state.output = ""; | ||
| for (const token of state.tokens) { | ||
| state.output += token.output != null ? token.output : token.value; | ||
| if (token.suffix) state.output += token.suffix; | ||
| } | ||
| } | ||
| return state; | ||
| }; | ||
| /** | ||
| * Fast paths for creating regular expressions for common glob patterns. | ||
| * This can significantly speed up processing and has very little downside | ||
| * impact when none of the fast paths match. | ||
| */ | ||
| parse$1.fastpaths = (input, options) => { | ||
| const opts = { ...options }; | ||
| const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; | ||
| const len = input.length; | ||
| if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); | ||
| input = REPLACEMENTS[input] || input; | ||
| const { DOT_LITERAL: DOT_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR: START_ANCHOR$1 } = constants$1.globChars(opts.windows); | ||
| const nodot = opts.dot ? NO_DOTS : NO_DOT; | ||
| const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; | ||
| const capture = opts.capture ? "" : "?:"; | ||
| const state = { | ||
| negated: false, | ||
| prefix: "" | ||
| }; | ||
| let star = opts.bash === true ? ".*?" : STAR; | ||
| if (opts.capture) star = `(${star})`; | ||
| const globstar = (opts$1) => { | ||
| if (opts$1.noglobstar === true) return star; | ||
| return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`; | ||
| }; | ||
| const create = (str) => { | ||
| switch (str) { | ||
| case "*": return `${nodot}${ONE_CHAR$1}${star}`; | ||
| case ".*": return `${DOT_LITERAL$1}${ONE_CHAR$1}${star}`; | ||
| case "*.*": return `${nodot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`; | ||
| case "*/*": return `${nodot}${star}${SLASH_LITERAL$1}${ONE_CHAR$1}${slashDot}${star}`; | ||
| case "**": return nodot + globstar(opts); | ||
| case "**/*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${ONE_CHAR$1}${star}`; | ||
| case "**/*.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`; | ||
| case "**/.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${DOT_LITERAL$1}${ONE_CHAR$1}${star}`; | ||
| default: { | ||
| const match = /^(.*?)\.(\w+)$/.exec(str); | ||
| if (!match) return; | ||
| const source$1 = create(match[1]); | ||
| if (!source$1) return; | ||
| return source$1 + DOT_LITERAL$1 + match[2]; | ||
| } | ||
| } | ||
| }; | ||
| let source = create(utils$2.removePrefix(input, state)); | ||
| if (source && opts.strictSlashes !== true) source += `${SLASH_LITERAL$1}?`; | ||
| return source; | ||
| }; | ||
| module.exports = parse$1; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js | ||
| var require_picomatch$1 = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js": ((exports, module) => { | ||
| const scan = require_scan(); | ||
| const parse = require_parse(); | ||
| const utils$1 = require_utils(); | ||
| const constants = require_constants(); | ||
| const isObject = (val) => val && typeof val === "object" && !Array.isArray(val); | ||
| /** | ||
| * Creates a matcher function from one or more glob patterns. The | ||
| * returned function takes a string to match as its first argument, | ||
| * and returns true if the string is a match. The returned matcher | ||
| * function also takes a boolean as the second argument that, when true, | ||
| * returns an object with additional information. | ||
| * | ||
| * ```js | ||
| * const picomatch = require('picomatch'); | ||
| * // picomatch(glob[, options]); | ||
| * | ||
| * const isMatch = picomatch('*.!(*a)'); | ||
| * console.log(isMatch('a.a')); //=> false | ||
| * console.log(isMatch('a.b')); //=> true | ||
| * ``` | ||
| * @name picomatch | ||
| * @param {String|Array} `globs` One or more glob patterns. | ||
| * @param {Object=} `options` | ||
| * @return {Function=} Returns a matcher function. | ||
| * @api public | ||
| */ | ||
| const picomatch$1 = (glob, options, returnState = false) => { | ||
| if (Array.isArray(glob)) { | ||
| const fns = glob.map((input) => picomatch$1(input, options, returnState)); | ||
| const arrayMatcher = (str) => { | ||
| for (const isMatch of fns) { | ||
| const state$1 = isMatch(str); | ||
| if (state$1) return state$1; | ||
| } | ||
| return false; | ||
| }; | ||
| return arrayMatcher; | ||
| } | ||
| const isState = isObject(glob) && glob.tokens && glob.input; | ||
| if (glob === "" || typeof glob !== "string" && !isState) throw new TypeError("Expected pattern to be a non-empty string"); | ||
| const opts = options || {}; | ||
| const posix = opts.windows; | ||
| const regex = isState ? picomatch$1.compileRe(glob, options) : picomatch$1.makeRe(glob, options, false, true); | ||
| const state = regex.state; | ||
| delete regex.state; | ||
| let isIgnored = () => false; | ||
| if (opts.ignore) { | ||
| const ignoreOpts = { | ||
| ...options, | ||
| ignore: null, | ||
| onMatch: null, | ||
| onResult: null | ||
| }; | ||
| isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState); | ||
| } | ||
| const matcher = (input, returnObject = false) => { | ||
| const { isMatch, match, output } = picomatch$1.test(input, regex, options, { | ||
| glob, | ||
| posix | ||
| }); | ||
| const result = { | ||
| glob, | ||
| state, | ||
| regex, | ||
| posix, | ||
| input, | ||
| output, | ||
| match, | ||
| isMatch | ||
| }; | ||
| if (typeof opts.onResult === "function") opts.onResult(result); | ||
| if (isMatch === false) { | ||
| result.isMatch = false; | ||
| return returnObject ? result : false; | ||
| } | ||
| if (isIgnored(input)) { | ||
| if (typeof opts.onIgnore === "function") opts.onIgnore(result); | ||
| result.isMatch = false; | ||
| return returnObject ? result : false; | ||
| } | ||
| if (typeof opts.onMatch === "function") opts.onMatch(result); | ||
| return returnObject ? result : true; | ||
| }; | ||
| if (returnState) matcher.state = state; | ||
| return matcher; | ||
| }; | ||
| /** | ||
| * Test `input` with the given `regex`. This is used by the main | ||
| * `picomatch()` function to test the input string. | ||
| * | ||
| * ```js | ||
| * const picomatch = require('picomatch'); | ||
| * // picomatch.test(input, regex[, options]); | ||
| * | ||
| * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); | ||
| * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } | ||
| * ``` | ||
| * @param {String} `input` String to test. | ||
| * @param {RegExp} `regex` | ||
| * @return {Object} Returns an object with matching info. | ||
| * @api public | ||
| */ | ||
| picomatch$1.test = (input, regex, options, { glob, posix } = {}) => { | ||
| if (typeof input !== "string") throw new TypeError("Expected input to be a string"); | ||
| if (input === "") return { | ||
| isMatch: false, | ||
| output: "" | ||
| }; | ||
| const opts = options || {}; | ||
| const format = opts.format || (posix ? utils$1.toPosixSlashes : null); | ||
| let match = input === glob; | ||
| let output = match && format ? format(input) : input; | ||
| if (match === false) { | ||
| output = format ? format(input) : input; | ||
| match = output === glob; | ||
| } | ||
| if (match === false || opts.capture === true) if (opts.matchBase === true || opts.basename === true) match = picomatch$1.matchBase(input, regex, options, posix); | ||
| else match = regex.exec(output); | ||
| return { | ||
| isMatch: Boolean(match), | ||
| match, | ||
| output | ||
| }; | ||
| }; | ||
| /** | ||
| * Match the basename of a filepath. | ||
| * | ||
| * ```js | ||
| * const picomatch = require('picomatch'); | ||
| * // picomatch.matchBase(input, glob[, options]); | ||
| * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true | ||
| * ``` | ||
| * @param {String} `input` String to test. | ||
| * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). | ||
| * @return {Boolean} | ||
| * @api public | ||
| */ | ||
| picomatch$1.matchBase = (input, glob, options) => { | ||
| return (glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options)).test(utils$1.basename(input)); | ||
| }; | ||
| /** | ||
| * Returns true if **any** of the given glob `patterns` match the specified `string`. | ||
| * | ||
| * ```js | ||
| * const picomatch = require('picomatch'); | ||
| * // picomatch.isMatch(string, patterns[, options]); | ||
| * | ||
| * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true | ||
| * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false | ||
| * ``` | ||
| * @param {String|Array} str The string to test. | ||
| * @param {String|Array} patterns One or more glob patterns to use for matching. | ||
| * @param {Object} [options] See available [options](#options). | ||
| * @return {Boolean} Returns true if any patterns match `str` | ||
| * @api public | ||
| */ | ||
| picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str); | ||
| /** | ||
| * Parse a glob pattern to create the source string for a regular | ||
| * expression. | ||
| * | ||
| * ```js | ||
| * const picomatch = require('picomatch'); | ||
| * const result = picomatch.parse(pattern[, options]); | ||
| * ``` | ||
| * @param {String} `pattern` | ||
| * @param {Object} `options` | ||
| * @return {Object} Returns an object with useful properties and output to be used as a regex source string. | ||
| * @api public | ||
| */ | ||
| picomatch$1.parse = (pattern, options) => { | ||
| if (Array.isArray(pattern)) return pattern.map((p) => picomatch$1.parse(p, options)); | ||
| return parse(pattern, { | ||
| ...options, | ||
| fastpaths: false | ||
| }); | ||
| }; | ||
| /** | ||
| * Scan a glob pattern to separate the pattern into segments. | ||
| * | ||
| * ```js | ||
| * const picomatch = require('picomatch'); | ||
| * // picomatch.scan(input[, options]); | ||
| * | ||
| * const result = picomatch.scan('!./foo/*.js'); | ||
| * console.log(result); | ||
| * { prefix: '!./', | ||
| * input: '!./foo/*.js', | ||
| * start: 3, | ||
| * base: 'foo', | ||
| * glob: '*.js', | ||
| * isBrace: false, | ||
| * isBracket: false, | ||
| * isGlob: true, | ||
| * isExtglob: false, | ||
| * isGlobstar: false, | ||
| * negated: true } | ||
| * ``` | ||
| * @param {String} `input` Glob pattern to scan. | ||
| * @param {Object} `options` | ||
| * @return {Object} Returns an object with | ||
| * @api public | ||
| */ | ||
| picomatch$1.scan = (input, options) => scan(input, options); | ||
| /** | ||
| * Compile a regular expression from the `state` object returned by the | ||
| * [parse()](#parse) method. | ||
| * | ||
| * @param {Object} `state` | ||
| * @param {Object} `options` | ||
| * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. | ||
| * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. | ||
| * @return {RegExp} | ||
| * @api public | ||
| */ | ||
| picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => { | ||
| if (returnOutput === true) return state.output; | ||
| const opts = options || {}; | ||
| const prepend = opts.contains ? "" : "^"; | ||
| const append = opts.contains ? "" : "$"; | ||
| let source = `${prepend}(?:${state.output})${append}`; | ||
| if (state && state.negated === true) source = `^(?!${source}).*$`; | ||
| const regex = picomatch$1.toRegex(source, options); | ||
| if (returnState === true) regex.state = state; | ||
| return regex; | ||
| }; | ||
| /** | ||
| * Create a regular expression from a parsed glob pattern. | ||
| * | ||
| * ```js | ||
| * const picomatch = require('picomatch'); | ||
| * const state = picomatch.parse('*.js'); | ||
| * // picomatch.compileRe(state[, options]); | ||
| * | ||
| * console.log(picomatch.compileRe(state)); | ||
| * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ | ||
| * ``` | ||
| * @param {String} `state` The object returned from the `.parse` method. | ||
| * @param {Object} `options` | ||
| * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. | ||
| * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. | ||
| * @return {RegExp} Returns a regex created from the given pattern. | ||
| * @api public | ||
| */ | ||
| picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { | ||
| if (!input || typeof input !== "string") throw new TypeError("Expected a non-empty string"); | ||
| let parsed = { | ||
| negated: false, | ||
| fastpaths: true | ||
| }; | ||
| if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) parsed.output = parse.fastpaths(input, options); | ||
| if (!parsed.output) parsed = parse(input, options); | ||
| return picomatch$1.compileRe(parsed, options, returnOutput, returnState); | ||
| }; | ||
| /** | ||
| * Create a regular expression from the given regex source string. | ||
| * | ||
| * ```js | ||
| * const picomatch = require('picomatch'); | ||
| * // picomatch.toRegex(source[, options]); | ||
| * | ||
| * const { output } = picomatch.parse('*.js'); | ||
| * console.log(picomatch.toRegex(output)); | ||
| * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ | ||
| * ``` | ||
| * @param {String} `source` Regular expression source string. | ||
| * @param {Object} `options` | ||
| * @return {RegExp} | ||
| * @api public | ||
| */ | ||
| picomatch$1.toRegex = (source, options) => { | ||
| try { | ||
| const opts = options || {}; | ||
| return new RegExp(source, opts.flags || (opts.nocase ? "i" : "")); | ||
| } catch (err) { | ||
| if (options && options.debug === true) throw err; | ||
| return /$^/; | ||
| } | ||
| }; | ||
| /** | ||
| * Picomatch constants. | ||
| * @return {Object} | ||
| */ | ||
| picomatch$1.constants = constants; | ||
| /** | ||
| * Expose "picomatch" | ||
| */ | ||
| module.exports = picomatch$1; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js | ||
| var require_picomatch = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js": ((exports, module) => { | ||
| const pico = require_picomatch$1(); | ||
| const utils = require_utils(); | ||
| function picomatch(glob, options, returnState = false) { | ||
| if (options && (options.windows === null || options.windows === void 0)) options = { | ||
| ...options, | ||
| windows: utils.isWindows() | ||
| }; | ||
| return pico(glob, options, returnState); | ||
| } | ||
| Object.assign(picomatch, pico); | ||
| module.exports = picomatch; | ||
| }) }); | ||
| //#endregion | ||
| export { require_picomatch as t }; |
Sorry, the diff of this file is too big to display
| import { i as __toESM, n as __require, t as __commonJS } from "../_chunks/Bqks5huO.mjs"; | ||
| import { r as createFilter } from "./plugin-commonjs.mjs"; | ||
| import { t as require_cjs } from "./deepmerge.mjs"; | ||
| import { t as require_is_module } from "./is-module.mjs"; | ||
| import { t as require_path_parse } from "./path-parse.mjs"; | ||
| import { t as require_is_core_module } from "./is-core-module.mjs"; | ||
| import nativeFs, { realpathSync } from "fs"; | ||
| import path, { dirname, extname, normalize, resolve, sep } from "path"; | ||
| import { fileURLToPath, pathToFileURL } from "url"; | ||
| import { builtinModules } from "module"; | ||
| import { promisify } from "util"; | ||
| //#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/homedir.js | ||
| var require_homedir = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/homedir.js": ((exports, module) => { | ||
| var os = __require("os"); | ||
| module.exports = os.homedir || function homedir$2() { | ||
| var home = process.env.HOME; | ||
| var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME; | ||
| if (process.platform === "win32") return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null; | ||
| if (process.platform === "darwin") return home || (user ? "/Users/" + user : null); | ||
| if (process.platform === "linux") return home || (process.getuid() === 0 ? "/root" : user ? "/home/" + user : null); | ||
| return home || null; | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/caller.js | ||
| var require_caller = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/caller.js": ((exports, module) => { | ||
| module.exports = function() { | ||
| var origPrepareStackTrace = Error.prepareStackTrace; | ||
| Error.prepareStackTrace = function(_, stack$1) { | ||
| return stack$1; | ||
| }; | ||
| var stack = (/* @__PURE__ */ new Error()).stack; | ||
| Error.prepareStackTrace = origPrepareStackTrace; | ||
| return stack[2].getFileName(); | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/node-modules-paths.js | ||
| var require_node_modules_paths = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/node-modules-paths.js": ((exports, module) => { | ||
| var path$3 = __require("path"); | ||
| var parse = path$3.parse || require_path_parse(); | ||
| var driveLetterRegex = /^([A-Za-z]:)/; | ||
| var uncPathRegex = /^\\\\/; | ||
| var getNodeModulesDirs = function getNodeModulesDirs$1(absoluteStart, modules) { | ||
| var prefix = "/"; | ||
| if (driveLetterRegex.test(absoluteStart)) prefix = ""; | ||
| else if (uncPathRegex.test(absoluteStart)) prefix = "\\\\"; | ||
| var paths = [absoluteStart]; | ||
| var parsed = parse(absoluteStart); | ||
| while (parsed.dir !== paths[paths.length - 1]) { | ||
| paths.push(parsed.dir); | ||
| parsed = parse(parsed.dir); | ||
| } | ||
| return paths.reduce(function(dirs, aPath) { | ||
| return dirs.concat(modules.map(function(moduleDir) { | ||
| return path$3.resolve(prefix, aPath, moduleDir); | ||
| })); | ||
| }, []); | ||
| }; | ||
| module.exports = function nodeModulesPaths$2(start, opts, request) { | ||
| var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ["node_modules"]; | ||
| if (opts && typeof opts.paths === "function") return opts.paths(request, start, function() { | ||
| return getNodeModulesDirs(start, modules); | ||
| }, opts); | ||
| var dirs = getNodeModulesDirs(start, modules); | ||
| return opts && opts.paths ? dirs.concat(opts.paths) : dirs; | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/normalize-options.js | ||
| var require_normalize_options = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/normalize-options.js": ((exports, module) => { | ||
| module.exports = function(x, opts) { | ||
| /** | ||
| * This file is purposefully a passthrough. It's expected that third-party | ||
| * environments will override it at runtime in order to inject special logic | ||
| * into `resolve` (by manipulating the options). One such example is the PnP | ||
| * code path in Yarn. | ||
| */ | ||
| return opts || {}; | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/async.js | ||
| var require_async = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/async.js": ((exports, module) => { | ||
| var fs$1 = __require("fs"); | ||
| var getHomedir$1 = require_homedir(); | ||
| var path$2 = __require("path"); | ||
| var caller$1 = require_caller(); | ||
| var nodeModulesPaths$1 = require_node_modules_paths(); | ||
| var normalizeOptions$1 = require_normalize_options(); | ||
| var isCore$1 = require_is_core_module(); | ||
| var realpathFS$1 = process.platform !== "win32" && fs$1.realpath && typeof fs$1.realpath.native === "function" ? fs$1.realpath.native : fs$1.realpath; | ||
| var relativePathRegex$1 = /^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/; | ||
| var windowsDriveRegex$1 = /^\w:[/\\]*$/; | ||
| var nodeModulesRegex$1 = /[/\\]node_modules[/\\]*$/; | ||
| var homedir$1 = getHomedir$1(); | ||
| var defaultPaths$1 = function() { | ||
| return [path$2.join(homedir$1, ".node_modules"), path$2.join(homedir$1, ".node_libraries")]; | ||
| }; | ||
| var defaultIsFile$1 = function isFile(file, cb) { | ||
| fs$1.stat(file, function(err, stat$2) { | ||
| if (!err) return cb(null, stat$2.isFile() || stat$2.isFIFO()); | ||
| if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb(null, false); | ||
| return cb(err); | ||
| }); | ||
| }; | ||
| var defaultIsDir$1 = function isDirectory(dir, cb) { | ||
| fs$1.stat(dir, function(err, stat$2) { | ||
| if (!err) return cb(null, stat$2.isDirectory()); | ||
| if (err.code === "ENOENT" || err.code === "ENOTDIR") return cb(null, false); | ||
| return cb(err); | ||
| }); | ||
| }; | ||
| var defaultRealpath = function realpath$1(x, cb) { | ||
| realpathFS$1(x, function(realpathErr, realPath) { | ||
| if (realpathErr && realpathErr.code !== "ENOENT") cb(realpathErr); | ||
| else cb(null, realpathErr ? x : realPath); | ||
| }); | ||
| }; | ||
| var maybeRealpath = function maybeRealpath$1(realpath$1, x, opts, cb) { | ||
| if (opts && opts.preserveSymlinks === false) realpath$1(x, cb); | ||
| else cb(null, x); | ||
| }; | ||
| var defaultReadPackage = function defaultReadPackage$1(readFile$2, pkgfile, cb) { | ||
| readFile$2(pkgfile, function(readFileErr, body) { | ||
| if (readFileErr) cb(readFileErr); | ||
| else try { | ||
| cb(null, JSON.parse(body)); | ||
| } catch (jsonErr) { | ||
| cb(null); | ||
| } | ||
| }); | ||
| }; | ||
| var getPackageCandidates$1 = function getPackageCandidates$2(x, start, opts) { | ||
| var dirs = nodeModulesPaths$1(start, opts, x); | ||
| for (var i = 0; i < dirs.length; i++) dirs[i] = path$2.join(dirs[i], x); | ||
| return dirs; | ||
| }; | ||
| module.exports = function resolve$2(x, options, callback) { | ||
| var cb = callback; | ||
| var opts = options; | ||
| if (typeof options === "function") { | ||
| cb = opts; | ||
| opts = {}; | ||
| } | ||
| if (typeof x !== "string") { | ||
| var err = /* @__PURE__ */ new TypeError("Path must be a string."); | ||
| return process.nextTick(function() { | ||
| cb(err); | ||
| }); | ||
| } | ||
| opts = normalizeOptions$1(x, opts); | ||
| var isFile = opts.isFile || defaultIsFile$1; | ||
| var isDirectory = opts.isDirectory || defaultIsDir$1; | ||
| var readFile$2 = opts.readFile || fs$1.readFile; | ||
| var realpath$1 = opts.realpath || defaultRealpath; | ||
| var readPackage = opts.readPackage || defaultReadPackage; | ||
| if (opts.readFile && opts.readPackage) { | ||
| var conflictErr = /* @__PURE__ */ new TypeError("`readFile` and `readPackage` are mutually exclusive."); | ||
| return process.nextTick(function() { | ||
| cb(conflictErr); | ||
| }); | ||
| } | ||
| var packageIterator = opts.packageIterator; | ||
| var extensions = opts.extensions || [".js"]; | ||
| var includeCoreModules = opts.includeCoreModules !== false; | ||
| var basedir = opts.basedir || path$2.dirname(caller$1()); | ||
| var parent = opts.filename || basedir; | ||
| opts.paths = opts.paths || defaultPaths$1(); | ||
| maybeRealpath(realpath$1, path$2.resolve(basedir), opts, function(err$1, realStart) { | ||
| if (err$1) cb(err$1); | ||
| else init(realStart); | ||
| }); | ||
| var res; | ||
| function init(basedir$1) { | ||
| if (relativePathRegex$1.test(x)) { | ||
| res = path$2.resolve(basedir$1, x); | ||
| if (x === "." || x === ".." || x.slice(-1) === "/") res += "/"; | ||
| if (x.slice(-1) === "/" && res === basedir$1) loadAsDirectory(res, opts.package, onfile); | ||
| else loadAsFile(res, opts.package, onfile); | ||
| } else if (includeCoreModules && isCore$1(x)) return cb(null, x); | ||
| else loadNodeModules(x, basedir$1, function(err$1, n, pkg) { | ||
| if (err$1) cb(err$1); | ||
| else if (n) return maybeRealpath(realpath$1, n, opts, function(err$2, realN) { | ||
| if (err$2) cb(err$2); | ||
| else cb(null, realN, pkg); | ||
| }); | ||
| else { | ||
| var moduleError = /* @__PURE__ */ new Error("Cannot find module '" + x + "' from '" + parent + "'"); | ||
| moduleError.code = "MODULE_NOT_FOUND"; | ||
| cb(moduleError); | ||
| } | ||
| }); | ||
| } | ||
| function onfile(err$1, m, pkg) { | ||
| if (err$1) cb(err$1); | ||
| else if (m) cb(null, m, pkg); | ||
| else loadAsDirectory(res, function(err$2, d, pkg$1) { | ||
| if (err$2) cb(err$2); | ||
| else if (d) maybeRealpath(realpath$1, d, opts, function(err$3, realD) { | ||
| if (err$3) cb(err$3); | ||
| else cb(null, realD, pkg$1); | ||
| }); | ||
| else { | ||
| var moduleError = /* @__PURE__ */ new Error("Cannot find module '" + x + "' from '" + parent + "'"); | ||
| moduleError.code = "MODULE_NOT_FOUND"; | ||
| cb(moduleError); | ||
| } | ||
| }); | ||
| } | ||
| function loadAsFile(x$1, thePackage, callback$1) { | ||
| var loadAsFilePackage = thePackage; | ||
| var cb$1 = callback$1; | ||
| if (typeof loadAsFilePackage === "function") { | ||
| cb$1 = loadAsFilePackage; | ||
| loadAsFilePackage = void 0; | ||
| } | ||
| load([""].concat(extensions), x$1, loadAsFilePackage); | ||
| function load(exts, x$2, loadPackage) { | ||
| if (exts.length === 0) return cb$1(null, void 0, loadPackage); | ||
| var file = x$2 + exts[0]; | ||
| var pkg = loadPackage; | ||
| if (pkg) onpkg(null, pkg); | ||
| else loadpkg(path$2.dirname(file), onpkg); | ||
| function onpkg(err$1, pkg_, dir) { | ||
| pkg = pkg_; | ||
| if (err$1) return cb$1(err$1); | ||
| if (dir && pkg && opts.pathFilter) { | ||
| var rfile = path$2.relative(dir, file); | ||
| var rel = rfile.slice(0, rfile.length - exts[0].length); | ||
| var r = opts.pathFilter(pkg, x$2, rel); | ||
| if (r) return load([""].concat(extensions.slice()), path$2.resolve(dir, r), pkg); | ||
| } | ||
| isFile(file, onex); | ||
| } | ||
| function onex(err$1, ex) { | ||
| if (err$1) return cb$1(err$1); | ||
| if (ex) return cb$1(null, file, pkg); | ||
| load(exts.slice(1), x$2, pkg); | ||
| } | ||
| } | ||
| } | ||
| function loadpkg(dir, cb$1) { | ||
| if (dir === "" || dir === "/") return cb$1(null); | ||
| if (process.platform === "win32" && windowsDriveRegex$1.test(dir)) return cb$1(null); | ||
| if (nodeModulesRegex$1.test(dir)) return cb$1(null); | ||
| maybeRealpath(realpath$1, dir, opts, function(unwrapErr, pkgdir) { | ||
| if (unwrapErr) return loadpkg(path$2.dirname(dir), cb$1); | ||
| var pkgfile = path$2.join(pkgdir, "package.json"); | ||
| isFile(pkgfile, function(err$1, ex) { | ||
| if (!ex) return loadpkg(path$2.dirname(dir), cb$1); | ||
| readPackage(readFile$2, pkgfile, function(err$2, pkgParam) { | ||
| if (err$2) cb$1(err$2); | ||
| var pkg = pkgParam; | ||
| if (pkg && opts.packageFilter) pkg = opts.packageFilter(pkg, pkgfile); | ||
| cb$1(null, pkg, dir); | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| function loadAsDirectory(x$1, loadAsDirectoryPackage, callback$1) { | ||
| var cb$1 = callback$1; | ||
| var fpkg = loadAsDirectoryPackage; | ||
| if (typeof fpkg === "function") { | ||
| cb$1 = fpkg; | ||
| fpkg = opts.package; | ||
| } | ||
| maybeRealpath(realpath$1, x$1, opts, function(unwrapErr, pkgdir) { | ||
| if (unwrapErr) return cb$1(unwrapErr); | ||
| var pkgfile = path$2.join(pkgdir, "package.json"); | ||
| isFile(pkgfile, function(err$1, ex) { | ||
| if (err$1) return cb$1(err$1); | ||
| if (!ex) return loadAsFile(path$2.join(x$1, "index"), fpkg, cb$1); | ||
| readPackage(readFile$2, pkgfile, function(err$2, pkgParam) { | ||
| if (err$2) return cb$1(err$2); | ||
| var pkg = pkgParam; | ||
| if (pkg && opts.packageFilter) pkg = opts.packageFilter(pkg, pkgfile); | ||
| if (pkg && pkg.main) { | ||
| if (typeof pkg.main !== "string") { | ||
| var mainError = /* @__PURE__ */ new TypeError("package “" + pkg.name + "” `main` must be a string"); | ||
| mainError.code = "INVALID_PACKAGE_MAIN"; | ||
| return cb$1(mainError); | ||
| } | ||
| if (pkg.main === "." || pkg.main === "./") pkg.main = "index"; | ||
| loadAsFile(path$2.resolve(x$1, pkg.main), pkg, function(err$3, m, pkg$1) { | ||
| if (err$3) return cb$1(err$3); | ||
| if (m) return cb$1(null, m, pkg$1); | ||
| if (!pkg$1) return loadAsFile(path$2.join(x$1, "index"), pkg$1, cb$1); | ||
| loadAsDirectory(path$2.resolve(x$1, pkg$1.main), pkg$1, function(err$4, n, pkg$2) { | ||
| if (err$4) return cb$1(err$4); | ||
| if (n) return cb$1(null, n, pkg$2); | ||
| loadAsFile(path$2.join(x$1, "index"), pkg$2, cb$1); | ||
| }); | ||
| }); | ||
| return; | ||
| } | ||
| loadAsFile(path$2.join(x$1, "/index"), pkg, cb$1); | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| function processDirs(cb$1, dirs) { | ||
| if (dirs.length === 0) return cb$1(null, void 0); | ||
| var dir = dirs[0]; | ||
| isDirectory(path$2.dirname(dir), isdir); | ||
| function isdir(err$1, isdir$1) { | ||
| if (err$1) return cb$1(err$1); | ||
| if (!isdir$1) return processDirs(cb$1, dirs.slice(1)); | ||
| loadAsFile(dir, opts.package, onfile$1); | ||
| } | ||
| function onfile$1(err$1, m, pkg) { | ||
| if (err$1) return cb$1(err$1); | ||
| if (m) return cb$1(null, m, pkg); | ||
| loadAsDirectory(dir, opts.package, ondir); | ||
| } | ||
| function ondir(err$1, n, pkg) { | ||
| if (err$1) return cb$1(err$1); | ||
| if (n) return cb$1(null, n, pkg); | ||
| processDirs(cb$1, dirs.slice(1)); | ||
| } | ||
| } | ||
| function loadNodeModules(x$1, start, cb$1) { | ||
| var thunk = function() { | ||
| return getPackageCandidates$1(x$1, start, opts); | ||
| }; | ||
| processDirs(cb$1, packageIterator ? packageIterator(x$1, start, thunk, opts) : thunk()); | ||
| } | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/core.json | ||
| var require_core$1 = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/core.json": ((exports, module) => { | ||
| module.exports = { | ||
| "assert": true, | ||
| "node:assert": [">= 14.18 && < 15", ">= 16"], | ||
| "assert/strict": ">= 15", | ||
| "node:assert/strict": ">= 16", | ||
| "async_hooks": ">= 8", | ||
| "node:async_hooks": [">= 14.18 && < 15", ">= 16"], | ||
| "buffer_ieee754": ">= 0.5 && < 0.9.7", | ||
| "buffer": true, | ||
| "node:buffer": [">= 14.18 && < 15", ">= 16"], | ||
| "child_process": true, | ||
| "node:child_process": [">= 14.18 && < 15", ">= 16"], | ||
| "cluster": ">= 0.5", | ||
| "node:cluster": [">= 14.18 && < 15", ">= 16"], | ||
| "console": true, | ||
| "node:console": [">= 14.18 && < 15", ">= 16"], | ||
| "constants": true, | ||
| "node:constants": [">= 14.18 && < 15", ">= 16"], | ||
| "crypto": true, | ||
| "node:crypto": [">= 14.18 && < 15", ">= 16"], | ||
| "_debug_agent": ">= 1 && < 8", | ||
| "_debugger": "< 8", | ||
| "dgram": true, | ||
| "node:dgram": [">= 14.18 && < 15", ">= 16"], | ||
| "diagnostics_channel": [">= 14.17 && < 15", ">= 15.1"], | ||
| "node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"], | ||
| "dns": true, | ||
| "node:dns": [">= 14.18 && < 15", ">= 16"], | ||
| "dns/promises": ">= 15", | ||
| "node:dns/promises": ">= 16", | ||
| "domain": ">= 0.7.12", | ||
| "node:domain": [">= 14.18 && < 15", ">= 16"], | ||
| "events": true, | ||
| "node:events": [">= 14.18 && < 15", ">= 16"], | ||
| "freelist": "< 6", | ||
| "fs": true, | ||
| "node:fs": [">= 14.18 && < 15", ">= 16"], | ||
| "fs/promises": [">= 10 && < 10.1", ">= 14"], | ||
| "node:fs/promises": [">= 14.18 && < 15", ">= 16"], | ||
| "_http_agent": ">= 0.11.1", | ||
| "node:_http_agent": [">= 14.18 && < 15", ">= 16"], | ||
| "_http_client": ">= 0.11.1", | ||
| "node:_http_client": [">= 14.18 && < 15", ">= 16"], | ||
| "_http_common": ">= 0.11.1", | ||
| "node:_http_common": [">= 14.18 && < 15", ">= 16"], | ||
| "_http_incoming": ">= 0.11.1", | ||
| "node:_http_incoming": [">= 14.18 && < 15", ">= 16"], | ||
| "_http_outgoing": ">= 0.11.1", | ||
| "node:_http_outgoing": [">= 14.18 && < 15", ">= 16"], | ||
| "_http_server": ">= 0.11.1", | ||
| "node:_http_server": [">= 14.18 && < 15", ">= 16"], | ||
| "http": true, | ||
| "node:http": [">= 14.18 && < 15", ">= 16"], | ||
| "http2": ">= 8.8", | ||
| "node:http2": [">= 14.18 && < 15", ">= 16"], | ||
| "https": true, | ||
| "node:https": [">= 14.18 && < 15", ">= 16"], | ||
| "inspector": ">= 8", | ||
| "node:inspector": [">= 14.18 && < 15", ">= 16"], | ||
| "inspector/promises": [">= 19"], | ||
| "node:inspector/promises": [">= 19"], | ||
| "_linklist": "< 8", | ||
| "module": true, | ||
| "node:module": [">= 14.18 && < 15", ">= 16"], | ||
| "net": true, | ||
| "node:net": [">= 14.18 && < 15", ">= 16"], | ||
| "node-inspect/lib/_inspect": ">= 7.6 && < 12", | ||
| "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12", | ||
| "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12", | ||
| "os": true, | ||
| "node:os": [">= 14.18 && < 15", ">= 16"], | ||
| "path": true, | ||
| "node:path": [">= 14.18 && < 15", ">= 16"], | ||
| "path/posix": ">= 15.3", | ||
| "node:path/posix": ">= 16", | ||
| "path/win32": ">= 15.3", | ||
| "node:path/win32": ">= 16", | ||
| "perf_hooks": ">= 8.5", | ||
| "node:perf_hooks": [">= 14.18 && < 15", ">= 16"], | ||
| "process": ">= 1", | ||
| "node:process": [">= 14.18 && < 15", ">= 16"], | ||
| "punycode": ">= 0.5", | ||
| "node:punycode": [">= 14.18 && < 15", ">= 16"], | ||
| "querystring": true, | ||
| "node:querystring": [">= 14.18 && < 15", ">= 16"], | ||
| "readline": true, | ||
| "node:readline": [">= 14.18 && < 15", ">= 16"], | ||
| "readline/promises": ">= 17", | ||
| "node:readline/promises": ">= 17", | ||
| "repl": true, | ||
| "node:repl": [">= 14.18 && < 15", ">= 16"], | ||
| "node:sea": [">= 20.12 && < 21", ">= 21.7"], | ||
| "smalloc": ">= 0.11.5 && < 3", | ||
| "node:sqlite": [">= 22.13 && < 23", ">= 23.4"], | ||
| "_stream_duplex": ">= 0.9.4", | ||
| "node:_stream_duplex": [">= 14.18 && < 15", ">= 16"], | ||
| "_stream_transform": ">= 0.9.4", | ||
| "node:_stream_transform": [">= 14.18 && < 15", ">= 16"], | ||
| "_stream_wrap": ">= 1.4.1", | ||
| "node:_stream_wrap": [">= 14.18 && < 15", ">= 16"], | ||
| "_stream_passthrough": ">= 0.9.4", | ||
| "node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"], | ||
| "_stream_readable": ">= 0.9.4", | ||
| "node:_stream_readable": [">= 14.18 && < 15", ">= 16"], | ||
| "_stream_writable": ">= 0.9.4", | ||
| "node:_stream_writable": [">= 14.18 && < 15", ">= 16"], | ||
| "stream": true, | ||
| "node:stream": [">= 14.18 && < 15", ">= 16"], | ||
| "stream/consumers": ">= 16.7", | ||
| "node:stream/consumers": ">= 16.7", | ||
| "stream/promises": ">= 15", | ||
| "node:stream/promises": ">= 16", | ||
| "stream/web": ">= 16.5", | ||
| "node:stream/web": ">= 16.5", | ||
| "string_decoder": true, | ||
| "node:string_decoder": [">= 14.18 && < 15", ">= 16"], | ||
| "sys": [">= 0.4 && < 0.7", ">= 0.8"], | ||
| "node:sys": [">= 14.18 && < 15", ">= 16"], | ||
| "test/reporters": ">= 19.9 && < 20.2", | ||
| "node:test/reporters": [ | ||
| ">= 18.17 && < 19", | ||
| ">= 19.9", | ||
| ">= 20" | ||
| ], | ||
| "test/mock_loader": ">= 22.3 && < 22.7", | ||
| "node:test/mock_loader": ">= 22.3 && < 22.7", | ||
| "node:test": [">= 16.17 && < 17", ">= 18"], | ||
| "timers": true, | ||
| "node:timers": [">= 14.18 && < 15", ">= 16"], | ||
| "timers/promises": ">= 15", | ||
| "node:timers/promises": ">= 16", | ||
| "_tls_common": ">= 0.11.13", | ||
| "node:_tls_common": [">= 14.18 && < 15", ">= 16"], | ||
| "_tls_legacy": ">= 0.11.3 && < 10", | ||
| "_tls_wrap": ">= 0.11.3", | ||
| "node:_tls_wrap": [">= 14.18 && < 15", ">= 16"], | ||
| "tls": true, | ||
| "node:tls": [">= 14.18 && < 15", ">= 16"], | ||
| "trace_events": ">= 10", | ||
| "node:trace_events": [">= 14.18 && < 15", ">= 16"], | ||
| "tty": true, | ||
| "node:tty": [">= 14.18 && < 15", ">= 16"], | ||
| "url": true, | ||
| "node:url": [">= 14.18 && < 15", ">= 16"], | ||
| "util": true, | ||
| "node:util": [">= 14.18 && < 15", ">= 16"], | ||
| "util/types": ">= 15.3", | ||
| "node:util/types": ">= 16", | ||
| "v8/tools/arguments": ">= 10 && < 12", | ||
| "v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"], | ||
| "v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"], | ||
| "v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"], | ||
| "v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"], | ||
| "v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"], | ||
| "v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"], | ||
| "v8": ">= 1", | ||
| "node:v8": [">= 14.18 && < 15", ">= 16"], | ||
| "vm": true, | ||
| "node:vm": [">= 14.18 && < 15", ">= 16"], | ||
| "wasi": [ | ||
| ">= 13.4 && < 13.5", | ||
| ">= 18.17 && < 19", | ||
| ">= 20" | ||
| ], | ||
| "node:wasi": [">= 18.17 && < 19", ">= 20"], | ||
| "worker_threads": ">= 11.7", | ||
| "node:worker_threads": [">= 14.18 && < 15", ">= 16"], | ||
| "zlib": ">= 0.5", | ||
| "node:zlib": [">= 14.18 && < 15", ">= 16"] | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/core.js | ||
| var require_core = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/core.js": ((exports, module) => { | ||
| var isCoreModule$1 = require_is_core_module(); | ||
| var data = require_core$1(); | ||
| var core = {}; | ||
| for (var mod in data) if (Object.prototype.hasOwnProperty.call(data, mod)) core[mod] = isCoreModule$1(mod); | ||
| module.exports = core; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/is-core.js | ||
| var require_is_core = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/is-core.js": ((exports, module) => { | ||
| var isCoreModule = require_is_core_module(); | ||
| module.exports = function isCore$2(x) { | ||
| return isCoreModule(x); | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/sync.js | ||
| var require_sync = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/lib/sync.js": ((exports, module) => { | ||
| var isCore = require_is_core_module(); | ||
| var fs = __require("fs"); | ||
| var path$1 = __require("path"); | ||
| var getHomedir = require_homedir(); | ||
| var caller = require_caller(); | ||
| var nodeModulesPaths = require_node_modules_paths(); | ||
| var normalizeOptions = require_normalize_options(); | ||
| var realpathFS = process.platform !== "win32" && fs.realpathSync && typeof fs.realpathSync.native === "function" ? fs.realpathSync.native : fs.realpathSync; | ||
| var relativePathRegex = /^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/; | ||
| var windowsDriveRegex = /^\w:[/\\]*$/; | ||
| var nodeModulesRegex = /[/\\]node_modules[/\\]*$/; | ||
| var homedir = getHomedir(); | ||
| var defaultPaths = function() { | ||
| return [path$1.join(homedir, ".node_modules"), path$1.join(homedir, ".node_libraries")]; | ||
| }; | ||
| var defaultIsFile = function isFile(file) { | ||
| try { | ||
| var stat$2 = fs.statSync(file, { throwIfNoEntry: false }); | ||
| } catch (e) { | ||
| if (e && (e.code === "ENOENT" || e.code === "ENOTDIR")) return false; | ||
| throw e; | ||
| } | ||
| return !!stat$2 && (stat$2.isFile() || stat$2.isFIFO()); | ||
| }; | ||
| var defaultIsDir = function isDirectory(dir) { | ||
| try { | ||
| var stat$2 = fs.statSync(dir, { throwIfNoEntry: false }); | ||
| } catch (e) { | ||
| if (e && (e.code === "ENOENT" || e.code === "ENOTDIR")) return false; | ||
| throw e; | ||
| } | ||
| return !!stat$2 && stat$2.isDirectory(); | ||
| }; | ||
| var defaultRealpathSync = function realpathSync$1(x) { | ||
| try { | ||
| return realpathFS(x); | ||
| } catch (realpathErr) { | ||
| if (realpathErr.code !== "ENOENT") throw realpathErr; | ||
| } | ||
| return x; | ||
| }; | ||
| var maybeRealpathSync = function maybeRealpathSync$1(realpathSync$1, x, opts) { | ||
| if (opts && opts.preserveSymlinks === false) return realpathSync$1(x); | ||
| return x; | ||
| }; | ||
| var defaultReadPackageSync = function defaultReadPackageSync$1(readFileSync$1, pkgfile) { | ||
| var body = readFileSync$1(pkgfile); | ||
| try { | ||
| return JSON.parse(body); | ||
| } catch (jsonErr) {} | ||
| }; | ||
| var getPackageCandidates = function getPackageCandidates$2(x, start, opts) { | ||
| var dirs = nodeModulesPaths(start, opts, x); | ||
| for (var i = 0; i < dirs.length; i++) dirs[i] = path$1.join(dirs[i], x); | ||
| return dirs; | ||
| }; | ||
| module.exports = function resolveSync(x, options) { | ||
| if (typeof x !== "string") throw new TypeError("Path must be a string."); | ||
| var opts = normalizeOptions(x, options); | ||
| var isFile = opts.isFile || defaultIsFile; | ||
| var readFileSync$1 = opts.readFileSync || fs.readFileSync; | ||
| var isDirectory = opts.isDirectory || defaultIsDir; | ||
| var realpathSync$1 = opts.realpathSync || defaultRealpathSync; | ||
| var readPackageSync = opts.readPackageSync || defaultReadPackageSync; | ||
| if (opts.readFileSync && opts.readPackageSync) throw new TypeError("`readFileSync` and `readPackageSync` are mutually exclusive."); | ||
| var packageIterator = opts.packageIterator; | ||
| var extensions = opts.extensions || [".js"]; | ||
| var includeCoreModules = opts.includeCoreModules !== false; | ||
| var basedir = opts.basedir || path$1.dirname(caller()); | ||
| var parent = opts.filename || basedir; | ||
| opts.paths = opts.paths || defaultPaths(); | ||
| var absoluteStart = maybeRealpathSync(realpathSync$1, path$1.resolve(basedir), opts); | ||
| if (relativePathRegex.test(x)) { | ||
| var res = path$1.resolve(absoluteStart, x); | ||
| if (x === "." || x === ".." || x.slice(-1) === "/") res += "/"; | ||
| var m = loadAsFileSync(res) || loadAsDirectorySync(res); | ||
| if (m) return maybeRealpathSync(realpathSync$1, m, opts); | ||
| } else if (includeCoreModules && isCore(x)) return x; | ||
| else { | ||
| var n = loadNodeModulesSync(x, absoluteStart); | ||
| if (n) return maybeRealpathSync(realpathSync$1, n, opts); | ||
| } | ||
| var err = /* @__PURE__ */ new Error("Cannot find module '" + x + "' from '" + parent + "'"); | ||
| err.code = "MODULE_NOT_FOUND"; | ||
| throw err; | ||
| function loadAsFileSync(x$1) { | ||
| var pkg = loadpkg(path$1.dirname(x$1)); | ||
| if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { | ||
| var rfile = path$1.relative(pkg.dir, x$1); | ||
| var r = opts.pathFilter(pkg.pkg, x$1, rfile); | ||
| if (r) x$1 = path$1.resolve(pkg.dir, r); | ||
| } | ||
| if (isFile(x$1)) return x$1; | ||
| for (var i = 0; i < extensions.length; i++) { | ||
| var file = x$1 + extensions[i]; | ||
| if (isFile(file)) return file; | ||
| } | ||
| } | ||
| function loadpkg(dir) { | ||
| if (dir === "" || dir === "/") return; | ||
| if (process.platform === "win32" && windowsDriveRegex.test(dir)) return; | ||
| if (nodeModulesRegex.test(dir)) return; | ||
| var pkgfile = path$1.join(maybeRealpathSync(realpathSync$1, dir, opts), "package.json"); | ||
| if (!isFile(pkgfile)) return loadpkg(path$1.dirname(dir)); | ||
| var pkg = readPackageSync(readFileSync$1, pkgfile); | ||
| if (pkg && opts.packageFilter) pkg = opts.packageFilter(pkg, dir); | ||
| return { | ||
| pkg, | ||
| dir | ||
| }; | ||
| } | ||
| function loadAsDirectorySync(x$1) { | ||
| var pkgfile = path$1.join(maybeRealpathSync(realpathSync$1, x$1, opts), "/package.json"); | ||
| if (isFile(pkgfile)) { | ||
| try { | ||
| var pkg = readPackageSync(readFileSync$1, pkgfile); | ||
| } catch (e) {} | ||
| if (pkg && opts.packageFilter) pkg = opts.packageFilter(pkg, x$1); | ||
| if (pkg && pkg.main) { | ||
| if (typeof pkg.main !== "string") { | ||
| var mainError = /* @__PURE__ */ new TypeError("package “" + pkg.name + "” `main` must be a string"); | ||
| mainError.code = "INVALID_PACKAGE_MAIN"; | ||
| throw mainError; | ||
| } | ||
| if (pkg.main === "." || pkg.main === "./") pkg.main = "index"; | ||
| try { | ||
| var m$1 = loadAsFileSync(path$1.resolve(x$1, pkg.main)); | ||
| if (m$1) return m$1; | ||
| var n$1 = loadAsDirectorySync(path$1.resolve(x$1, pkg.main)); | ||
| if (n$1) return n$1; | ||
| } catch (e) {} | ||
| } | ||
| } | ||
| return loadAsFileSync(path$1.join(x$1, "/index")); | ||
| } | ||
| function loadNodeModulesSync(x$1, start) { | ||
| var thunk = function() { | ||
| return getPackageCandidates(x$1, start, opts); | ||
| }; | ||
| var dirs = packageIterator ? packageIterator(x$1, start, thunk, opts) : thunk(); | ||
| for (var i = 0; i < dirs.length; i++) { | ||
| var dir = dirs[i]; | ||
| if (isDirectory(path$1.dirname(dir))) { | ||
| var m$1 = loadAsFileSync(dir); | ||
| if (m$1) return m$1; | ||
| var n$1 = loadAsDirectorySync(dir); | ||
| if (n$1) return n$1; | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/index.js | ||
| var require_resolve = /* @__PURE__ */ __commonJS({ "node_modules/.pnpm/resolve@1.22.11/node_modules/resolve/index.js": ((exports, module) => { | ||
| var async = require_async(); | ||
| async.core = require_core(); | ||
| async.isCore = require_is_core(); | ||
| async.sync = require_sync(); | ||
| module.exports = async; | ||
| }) }); | ||
| //#endregion | ||
| //#region node_modules/.pnpm/@rollup+plugin-node-resolve@16.0.3_rollup@4.53.2/node_modules/@rollup/plugin-node-resolve/dist/es/index.js | ||
| var import_cjs = /* @__PURE__ */ __toESM(require_cjs(), 1); | ||
| var import_is_module = /* @__PURE__ */ __toESM(require_is_module(), 1); | ||
| var import_resolve = /* @__PURE__ */ __toESM(require_resolve(), 1); | ||
| var version = "16.0.3"; | ||
| var peerDependencies = { rollup: "^2.78.0||^3.0.0||^4.0.0" }; | ||
| promisify(nativeFs.access); | ||
| const readFile$1 = promisify(nativeFs.readFile); | ||
| const realpath = promisify(nativeFs.realpath); | ||
| const stat$1 = promisify(nativeFs.stat); | ||
| async function fileExists(filePath) { | ||
| try { | ||
| return (await stat$1(filePath)).isFile(); | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
| async function resolveSymlink(path$4) { | ||
| return await fileExists(path$4) ? realpath(path$4) : path$4; | ||
| } | ||
| const onError = (error) => { | ||
| if (error.code === "ENOENT") return false; | ||
| throw error; | ||
| }; | ||
| const makeCache = (fn) => { | ||
| const cache = /* @__PURE__ */ new Map(); | ||
| const wrapped = async (param, done) => { | ||
| if (cache.has(param) === false) cache.set(param, fn(param).catch((err) => { | ||
| cache.delete(param); | ||
| throw err; | ||
| })); | ||
| try { | ||
| return done(null, await cache.get(param)); | ||
| } catch (error) { | ||
| return done(error); | ||
| } | ||
| }; | ||
| wrapped.clear = () => cache.clear(); | ||
| return wrapped; | ||
| }; | ||
| const isDirCached = makeCache(async (file) => { | ||
| try { | ||
| return (await stat$1(file)).isDirectory(); | ||
| } catch (error) { | ||
| return onError(error); | ||
| } | ||
| }); | ||
| const isFileCached = makeCache(async (file) => { | ||
| try { | ||
| return (await stat$1(file)).isFile(); | ||
| } catch (error) { | ||
| return onError(error); | ||
| } | ||
| }); | ||
| const readCachedFile = makeCache(readFile$1); | ||
| function handleDeprecatedOptions(opts) { | ||
| const warnings = []; | ||
| if (opts.customResolveOptions) { | ||
| const { customResolveOptions } = opts; | ||
| if (customResolveOptions.moduleDirectory) { | ||
| opts.moduleDirectories = Array.isArray(customResolveOptions.moduleDirectory) ? customResolveOptions.moduleDirectory : [customResolveOptions.moduleDirectory]; | ||
| warnings.push("node-resolve: The `customResolveOptions.moduleDirectory` option has been deprecated. Use `moduleDirectories`, which must be an array."); | ||
| } | ||
| if (customResolveOptions.preserveSymlinks) throw new Error("node-resolve: `customResolveOptions.preserveSymlinks` is no longer an option. We now always use the rollup `preserveSymlinks` option."); | ||
| [ | ||
| "basedir", | ||
| "package", | ||
| "extensions", | ||
| "includeCoreModules", | ||
| "readFile", | ||
| "isFile", | ||
| "isDirectory", | ||
| "realpath", | ||
| "packageFilter", | ||
| "pathFilter", | ||
| "paths", | ||
| "packageIterator" | ||
| ].forEach((resolveOption) => { | ||
| if (customResolveOptions[resolveOption]) throw new Error(`node-resolve: \`customResolveOptions.${resolveOption}\` is no longer an option. If you need this, please open an issue.`); | ||
| }); | ||
| } | ||
| return { warnings }; | ||
| } | ||
| function getPackageName(id) { | ||
| if (id.startsWith(".") || id.startsWith("/")) return null; | ||
| const split = id.split("/"); | ||
| if (split[0][0] === "@") return `${split[0]}/${split[1]}`; | ||
| return split[0]; | ||
| } | ||
| function getMainFields(options) { | ||
| let mainFields; | ||
| if (options.mainFields) ({mainFields} = options); | ||
| else mainFields = ["module", "main"]; | ||
| if (options.browser && mainFields.indexOf("browser") === -1) return ["browser"].concat(mainFields); | ||
| if (!mainFields.length) throw new Error("Please ensure at least one `mainFields` value is specified"); | ||
| return mainFields; | ||
| } | ||
| function getPackageInfo(options) { | ||
| const { cache, extensions, pkg, mainFields, preserveSymlinks, useBrowserOverrides, rootDir, ignoreSideEffectsForRoot } = options; | ||
| let { pkgPath } = options; | ||
| if (cache.has(pkgPath)) return cache.get(pkgPath); | ||
| if (!preserveSymlinks) pkgPath = realpathSync(pkgPath); | ||
| const pkgRoot = dirname(pkgPath); | ||
| const packageInfo = { | ||
| packageJson: { ...pkg }, | ||
| packageJsonPath: pkgPath, | ||
| root: pkgRoot, | ||
| resolvedMainField: "main", | ||
| browserMappedMain: false, | ||
| resolvedEntryPoint: "" | ||
| }; | ||
| let overriddenMain = false; | ||
| for (let i = 0; i < mainFields.length; i++) { | ||
| const field = mainFields[i]; | ||
| if (typeof pkg[field] === "string") { | ||
| pkg.main = pkg[field]; | ||
| packageInfo.resolvedMainField = field; | ||
| overriddenMain = true; | ||
| break; | ||
| } | ||
| } | ||
| const internalPackageInfo = { | ||
| cachedPkg: pkg, | ||
| hasModuleSideEffects: () => null, | ||
| hasPackageEntry: overriddenMain !== false || mainFields.indexOf("main") !== -1, | ||
| packageBrowserField: useBrowserOverrides && typeof pkg.browser === "object" && Object.keys(pkg.browser).reduce((browser, key) => { | ||
| let resolved = pkg.browser[key]; | ||
| if (resolved && resolved[0] === ".") resolved = resolve(pkgRoot, resolved); | ||
| browser[key] = resolved; | ||
| if (key[0] === ".") { | ||
| const absoluteKey = resolve(pkgRoot, key); | ||
| browser[absoluteKey] = resolved; | ||
| if (!extname(key)) extensions.reduce((subBrowser, ext) => { | ||
| subBrowser[absoluteKey + ext] = subBrowser[key]; | ||
| return subBrowser; | ||
| }, browser); | ||
| } | ||
| return browser; | ||
| }, {}), | ||
| packageInfo | ||
| }; | ||
| const browserMap = internalPackageInfo.packageBrowserField; | ||
| if (useBrowserOverrides && typeof pkg.browser === "object" && browserMap.hasOwnProperty(pkg.main)) { | ||
| packageInfo.resolvedEntryPoint = browserMap[pkg.main]; | ||
| packageInfo.browserMappedMain = true; | ||
| } else { | ||
| packageInfo.resolvedEntryPoint = resolve(pkgRoot, pkg.main || "index.js"); | ||
| packageInfo.browserMappedMain = false; | ||
| } | ||
| if (!ignoreSideEffectsForRoot || rootDir !== pkgRoot) { | ||
| const packageSideEffects = pkg.sideEffects; | ||
| if (typeof packageSideEffects === "boolean") internalPackageInfo.hasModuleSideEffects = () => packageSideEffects; | ||
| else if (Array.isArray(packageSideEffects)) internalPackageInfo.hasModuleSideEffects = createFilter(packageSideEffects.map((sideEffect) => { | ||
| if (sideEffect.includes("/")) return sideEffect; | ||
| return `**/${sideEffect}`; | ||
| }), null, { resolve: pkgRoot }); | ||
| } | ||
| cache.set(pkgPath, internalPackageInfo); | ||
| return internalPackageInfo; | ||
| } | ||
| function normalizeInput(input) { | ||
| if (Array.isArray(input)) return input; | ||
| else if (typeof input === "object") return Object.values(input); | ||
| return [input]; | ||
| } | ||
| function isModuleDir(current, moduleDirs) { | ||
| return moduleDirs.some((dir) => current.endsWith(dir)); | ||
| } | ||
| async function findPackageJson(base, moduleDirs) { | ||
| const { root } = path.parse(base); | ||
| let current = base; | ||
| while (current !== root && !isModuleDir(current, moduleDirs)) { | ||
| const pkgJsonPath = path.join(current, "package.json"); | ||
| if (await fileExists(pkgJsonPath)) { | ||
| const pkgJsonString = nativeFs.readFileSync(pkgJsonPath, "utf-8"); | ||
| return { | ||
| pkgJson: JSON.parse(pkgJsonString), | ||
| pkgPath: current, | ||
| pkgJsonPath | ||
| }; | ||
| } | ||
| current = path.resolve(current, ".."); | ||
| } | ||
| return null; | ||
| } | ||
| function isUrl(str) { | ||
| try { | ||
| return !!new URL(str); | ||
| } catch (_) { | ||
| return false; | ||
| } | ||
| } | ||
| /** | ||
| * Conditions is an export object where all keys are conditions like 'node' (aka do not with '.') | ||
| */ | ||
| function isConditions(exports) { | ||
| return typeof exports === "object" && Object.keys(exports).every((k) => !k.startsWith(".")); | ||
| } | ||
| /** | ||
| * Mappings is an export object where all keys start with '. | ||
| */ | ||
| function isMappings(exports) { | ||
| return typeof exports === "object" && !isConditions(exports); | ||
| } | ||
| /** | ||
| * Check for mixed exports, which are exports where some keys start with '.' and some do not | ||
| */ | ||
| function isMixedExports(exports) { | ||
| const keys = Object.keys(exports); | ||
| return keys.some((k) => k.startsWith(".")) && keys.some((k) => !k.startsWith(".")); | ||
| } | ||
| function createBaseErrorMsg(importSpecifier, importer) { | ||
| return `Could not resolve import "${importSpecifier}" in ${importer}`; | ||
| } | ||
| function createErrorMsg(context, reason, isImports) { | ||
| const { importSpecifier, importer, pkgJsonPath } = context; | ||
| return `${createBaseErrorMsg(importSpecifier, importer)} using ${isImports ? "imports" : "exports"} defined in ${pkgJsonPath}.${reason ? ` ${reason}` : ""}`; | ||
| } | ||
| var ResolveError = class extends Error {}; | ||
| var InvalidConfigurationError = class extends ResolveError { | ||
| constructor(context, reason) { | ||
| super(createErrorMsg(context, `Invalid "exports" field. ${reason}`)); | ||
| } | ||
| }; | ||
| var InvalidModuleSpecifierError = class extends ResolveError { | ||
| constructor(context, isImports, reason) { | ||
| super(createErrorMsg(context, reason, isImports)); | ||
| } | ||
| }; | ||
| var InvalidPackageTargetError = class extends ResolveError { | ||
| constructor(context, reason) { | ||
| super(createErrorMsg(context, reason)); | ||
| } | ||
| }; | ||
| /** | ||
| * Check for invalid path segments | ||
| */ | ||
| function includesInvalidSegments(pathSegments, moduleDirs) { | ||
| const invalidSegments = [ | ||
| "", | ||
| ".", | ||
| "..", | ||
| ...moduleDirs | ||
| ]; | ||
| return pathSegments.some((v) => invalidSegments.includes(v) || invalidSegments.includes(decodeURI(v))); | ||
| } | ||
| async function resolvePackageTarget(context, { target, patternMatch, isImports }) { | ||
| if (typeof target === "string") { | ||
| if (!target.startsWith("./")) { | ||
| if (!isImports || ["/", "../"].some((p) => target.startsWith(p)) || isUrl(target)) throw new InvalidPackageTargetError(context, `Invalid mapping: "${target}".`); | ||
| if (typeof patternMatch === "string") { | ||
| const result$1 = await context.resolveId(target.replace(/\*/g, patternMatch), context.pkgURL.href); | ||
| return result$1 ? pathToFileURL(result$1.location).href : null; | ||
| } | ||
| const result = await context.resolveId(target, context.pkgURL.href); | ||
| return result ? pathToFileURL(result.location).href : null; | ||
| } | ||
| if (context.allowExportsFolderMapping) target = target.replace(/\/$/, "/*"); | ||
| { | ||
| const pathSegments = target.split(/\/|\\/); | ||
| const firstDot = pathSegments.indexOf("."); | ||
| firstDot !== -1 && pathSegments.slice(firstDot); | ||
| if (firstDot !== -1 && firstDot < pathSegments.length - 1 && includesInvalidSegments(pathSegments.slice(firstDot + 1), context.moduleDirs)) throw new InvalidPackageTargetError(context, `Invalid mapping: "${target}".`); | ||
| } | ||
| const resolvedTarget = new URL(target, context.pkgURL); | ||
| if (!resolvedTarget.href.startsWith(context.pkgURL.href)) throw new InvalidPackageTargetError(context, `Resolved to ${resolvedTarget.href} which is outside package ${context.pkgURL.href}`); | ||
| if (!patternMatch) return resolvedTarget; | ||
| if (includesInvalidSegments(patternMatch.split(/\/|\\/), context.moduleDirs)) throw new InvalidModuleSpecifierError(context); | ||
| return resolvedTarget.href.replace(/\*/g, patternMatch); | ||
| } | ||
| if (Array.isArray(target)) { | ||
| if (target.length === 0) return null; | ||
| let lastError = null; | ||
| for (const item of target) try { | ||
| const resolved = await resolvePackageTarget(context, { | ||
| target: item, | ||
| patternMatch, | ||
| isImports | ||
| }); | ||
| if (resolved !== void 0) return resolved; | ||
| } catch (error) { | ||
| if (!(error instanceof InvalidPackageTargetError)) throw error; | ||
| else lastError = error; | ||
| } | ||
| if (lastError) throw lastError; | ||
| return null; | ||
| } | ||
| if (target && typeof target === "object") { | ||
| for (const [key, value] of Object.entries(target)) if (key === "default" || context.conditions.includes(key)) { | ||
| const resolved = await resolvePackageTarget(context, { | ||
| target: value, | ||
| patternMatch, | ||
| isImports | ||
| }); | ||
| if (resolved !== void 0) return resolved; | ||
| } | ||
| return; | ||
| } | ||
| if (target === null) return null; | ||
| throw new InvalidPackageTargetError(context, `Invalid exports field.`); | ||
| } | ||
| /** | ||
| * Implementation of Node's `PATTERN_KEY_COMPARE` function | ||
| */ | ||
| function nodePatternKeyCompare(keyA, keyB) { | ||
| const baseLengthA = keyA.includes("*") ? keyA.indexOf("*") + 1 : keyA.length; | ||
| const rval = (keyB.includes("*") ? keyB.indexOf("*") + 1 : keyB.length) - baseLengthA; | ||
| if (rval !== 0) return rval; | ||
| if (!keyA.includes("*")) return 1; | ||
| if (!keyB.includes("*")) return -1; | ||
| return keyB.length - keyA.length; | ||
| } | ||
| async function resolvePackageImportsExports(context, { matchKey, matchObj, isImports }) { | ||
| if (!matchKey.includes("*") && matchKey in matchObj) { | ||
| const target = matchObj[matchKey]; | ||
| return await resolvePackageTarget(context, { | ||
| target, | ||
| patternMatch: "", | ||
| isImports | ||
| }); | ||
| } | ||
| const expansionKeys = Object.keys(matchObj).filter((k) => k.endsWith("/") || k.includes("*")).sort(nodePatternKeyCompare); | ||
| for (const expansionKey of expansionKeys) { | ||
| const indexOfAsterisk = expansionKey.indexOf("*"); | ||
| const patternBase = indexOfAsterisk === -1 ? expansionKey : expansionKey.substring(0, indexOfAsterisk); | ||
| if (matchKey.startsWith(patternBase) && matchKey !== patternBase) { | ||
| const patternTrailer = indexOfAsterisk !== -1 ? expansionKey.substring(indexOfAsterisk + 1) : ""; | ||
| if (patternTrailer.length === 0 || matchKey.endsWith(patternTrailer) && matchKey.length >= expansionKey.length) { | ||
| const target = matchObj[expansionKey]; | ||
| return await resolvePackageTarget(context, { | ||
| target, | ||
| patternMatch: matchKey.substring(patternBase.length, matchKey.length - patternTrailer.length), | ||
| isImports | ||
| }); | ||
| } | ||
| } | ||
| } | ||
| throw new InvalidModuleSpecifierError(context, isImports); | ||
| } | ||
| /** | ||
| * Implementation of PACKAGE_EXPORTS_RESOLVE | ||
| */ | ||
| async function resolvePackageExports(context, subpath, exports) { | ||
| if (isMixedExports(exports)) throw new InvalidConfigurationError(context, "All keys must either start with ./, or without one."); | ||
| if (subpath === ".") { | ||
| let mainExport; | ||
| if (typeof exports === "string" || Array.isArray(exports) || isConditions(exports)) mainExport = exports; | ||
| else if (isMappings(exports)) mainExport = exports["."]; | ||
| if (mainExport) { | ||
| const resolved = await resolvePackageTarget(context, { | ||
| target: mainExport, | ||
| patternMatch: "", | ||
| isImports: false | ||
| }); | ||
| if (resolved) return resolved; | ||
| } | ||
| } else if (isMappings(exports)) { | ||
| const resolvedMatch = await resolvePackageImportsExports(context, { | ||
| matchKey: subpath, | ||
| matchObj: exports, | ||
| isImports: false | ||
| }); | ||
| if (resolvedMatch) return resolvedMatch; | ||
| } | ||
| throw new InvalidModuleSpecifierError(context); | ||
| } | ||
| async function resolvePackageImports({ importSpecifier, importer, moduleDirs, conditions, resolveId }) { | ||
| const result = await findPackageJson(importer, moduleDirs); | ||
| if (!result) throw new Error(`${createBaseErrorMsg(importSpecifier, importer)}. Could not find a parent package.json.`); | ||
| const { pkgPath, pkgJsonPath, pkgJson } = result; | ||
| const context = { | ||
| importer, | ||
| importSpecifier, | ||
| moduleDirs, | ||
| pkgURL: pathToFileURL(`${pkgPath}/`), | ||
| pkgJsonPath, | ||
| conditions, | ||
| resolveId | ||
| }; | ||
| if (!importSpecifier.startsWith("#")) throw new InvalidModuleSpecifierError(context, true, "Invalid import specifier."); | ||
| if (importSpecifier === "#" || importSpecifier.startsWith("#/")) throw new InvalidModuleSpecifierError(context, true, "Invalid import specifier."); | ||
| const { imports } = pkgJson; | ||
| if (!imports) throw new InvalidModuleSpecifierError(context, true); | ||
| return resolvePackageImportsExports(context, { | ||
| matchKey: importSpecifier, | ||
| matchObj: imports, | ||
| isImports: true | ||
| }); | ||
| } | ||
| const resolveImportPath = promisify(import_resolve.default); | ||
| const readFile = promisify(nativeFs.readFile); | ||
| async function getPackageJson(importer, pkgName, resolveOptions, moduleDirectories) { | ||
| if (importer) { | ||
| const selfPackageJsonResult = await findPackageJson(importer, moduleDirectories); | ||
| if (selfPackageJsonResult && selfPackageJsonResult.pkgJson.name === pkgName) return selfPackageJsonResult; | ||
| } | ||
| try { | ||
| const pkgJsonPath = await resolveImportPath(`${pkgName}/package.json`, resolveOptions); | ||
| return { | ||
| pkgJsonPath, | ||
| pkgJson: JSON.parse(await readFile(pkgJsonPath, "utf-8")), | ||
| pkgPath: dirname(pkgJsonPath) | ||
| }; | ||
| } catch (_) { | ||
| return null; | ||
| } | ||
| } | ||
| async function resolveIdClassic({ importSpecifier, packageInfoCache, extensions, mainFields, preserveSymlinks, useBrowserOverrides, baseDir, moduleDirectories, modulePaths, rootDir, ignoreSideEffectsForRoot }) { | ||
| let hasModuleSideEffects = () => null; | ||
| let hasPackageEntry = true; | ||
| let packageBrowserField = false; | ||
| let packageInfo; | ||
| const filter = (pkg, pkgPath) => { | ||
| const info = getPackageInfo({ | ||
| cache: packageInfoCache, | ||
| extensions, | ||
| pkg, | ||
| pkgPath, | ||
| mainFields, | ||
| preserveSymlinks, | ||
| useBrowserOverrides, | ||
| rootDir, | ||
| ignoreSideEffectsForRoot | ||
| }); | ||
| ({packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField} = info); | ||
| return info.cachedPkg; | ||
| }; | ||
| const resolveOptions = { | ||
| basedir: baseDir, | ||
| readFile: readCachedFile, | ||
| isFile: isFileCached, | ||
| isDirectory: isDirCached, | ||
| extensions, | ||
| includeCoreModules: false, | ||
| moduleDirectory: moduleDirectories, | ||
| paths: modulePaths, | ||
| preserveSymlinks, | ||
| packageFilter: filter | ||
| }; | ||
| let location; | ||
| try { | ||
| location = await resolveImportPath(importSpecifier, resolveOptions); | ||
| } catch (error) { | ||
| if (error.code !== "MODULE_NOT_FOUND") throw error; | ||
| return null; | ||
| } | ||
| return { | ||
| location: preserveSymlinks ? location : await resolveSymlink(location), | ||
| hasModuleSideEffects, | ||
| hasPackageEntry, | ||
| packageBrowserField, | ||
| packageInfo | ||
| }; | ||
| } | ||
| async function resolveWithExportMap({ importer, importSpecifier, exportConditions, packageInfoCache, extensions, mainFields, preserveSymlinks, useBrowserOverrides, baseDir, moduleDirectories, modulePaths, rootDir, ignoreSideEffectsForRoot, allowExportsFolderMapping }) { | ||
| if (importSpecifier.startsWith("#")) { | ||
| const resolveResult = await resolvePackageImports({ | ||
| importSpecifier, | ||
| importer, | ||
| moduleDirs: moduleDirectories, | ||
| conditions: exportConditions, | ||
| resolveId(id) { | ||
| return resolveImportSpecifiers({ | ||
| importer, | ||
| importSpecifierList: [id], | ||
| exportConditions, | ||
| packageInfoCache, | ||
| extensions, | ||
| mainFields, | ||
| preserveSymlinks, | ||
| useBrowserOverrides, | ||
| baseDir, | ||
| moduleDirectories, | ||
| modulePaths, | ||
| rootDir, | ||
| ignoreSideEffectsForRoot, | ||
| allowExportsFolderMapping | ||
| }); | ||
| } | ||
| }); | ||
| if (resolveResult == null) throw new ResolveError(`Could not resolve import "${importSpecifier}" in ${importer} using imports.`); | ||
| const location = fileURLToPath(resolveResult); | ||
| return { | ||
| location: preserveSymlinks ? location : await resolveSymlink(location), | ||
| hasModuleSideEffects: () => null, | ||
| hasPackageEntry: true, | ||
| packageBrowserField: false, | ||
| packageInfo: void 0 | ||
| }; | ||
| } | ||
| const pkgName = getPackageName(importSpecifier); | ||
| if (pkgName) { | ||
| let hasModuleSideEffects = () => null; | ||
| let hasPackageEntry = true; | ||
| let packageBrowserField = false; | ||
| let packageInfo; | ||
| const filter = (pkg, pkgPath) => { | ||
| const info = getPackageInfo({ | ||
| cache: packageInfoCache, | ||
| extensions, | ||
| pkg, | ||
| pkgPath, | ||
| mainFields, | ||
| preserveSymlinks, | ||
| useBrowserOverrides, | ||
| rootDir, | ||
| ignoreSideEffectsForRoot | ||
| }); | ||
| ({packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField} = info); | ||
| return info.cachedPkg; | ||
| }; | ||
| const result = await getPackageJson(importer, pkgName, { | ||
| basedir: baseDir, | ||
| readFile: readCachedFile, | ||
| isFile: isFileCached, | ||
| isDirectory: isDirCached, | ||
| extensions, | ||
| includeCoreModules: false, | ||
| moduleDirectory: moduleDirectories, | ||
| paths: modulePaths, | ||
| preserveSymlinks, | ||
| packageFilter: filter | ||
| }, moduleDirectories); | ||
| if (result && result.pkgJson.exports) { | ||
| const { pkgJson, pkgJsonPath } = result; | ||
| const subpath = pkgName === importSpecifier ? "." : `.${importSpecifier.substring(pkgName.length)}`; | ||
| const location = fileURLToPath(await resolvePackageExports({ | ||
| importer, | ||
| importSpecifier, | ||
| moduleDirs: moduleDirectories, | ||
| pkgURL: pathToFileURL(pkgJsonPath.replace("package.json", "")), | ||
| pkgJsonPath, | ||
| allowExportsFolderMapping, | ||
| conditions: exportConditions | ||
| }, subpath, pkgJson.exports)); | ||
| if (location) return { | ||
| location: preserveSymlinks ? location : await resolveSymlink(location), | ||
| hasModuleSideEffects, | ||
| hasPackageEntry, | ||
| packageBrowserField, | ||
| packageInfo | ||
| }; | ||
| } | ||
| } | ||
| return null; | ||
| } | ||
| async function resolveWithClassic({ importer, importSpecifierList, exportConditions, warn, packageInfoCache, extensions, mainFields, preserveSymlinks, useBrowserOverrides, baseDir, moduleDirectories, modulePaths, rootDir, ignoreSideEffectsForRoot }) { | ||
| for (let i = 0; i < importSpecifierList.length; i++) { | ||
| const result = await resolveIdClassic({ | ||
| importer, | ||
| importSpecifier: importSpecifierList[i], | ||
| exportConditions, | ||
| warn, | ||
| packageInfoCache, | ||
| extensions, | ||
| mainFields, | ||
| preserveSymlinks, | ||
| useBrowserOverrides, | ||
| baseDir, | ||
| moduleDirectories, | ||
| modulePaths, | ||
| rootDir, | ||
| ignoreSideEffectsForRoot | ||
| }); | ||
| if (result) return result; | ||
| } | ||
| return null; | ||
| } | ||
| async function resolveImportSpecifiers({ importer, importSpecifierList, exportConditions, warn, packageInfoCache, extensions, mainFields, preserveSymlinks, useBrowserOverrides, baseDir, moduleDirectories, modulePaths, rootDir, ignoreSideEffectsForRoot, allowExportsFolderMapping }) { | ||
| try { | ||
| const exportMapRes = await resolveWithExportMap({ | ||
| importer, | ||
| importSpecifier: importSpecifierList[0], | ||
| exportConditions, | ||
| packageInfoCache, | ||
| extensions, | ||
| mainFields, | ||
| preserveSymlinks, | ||
| useBrowserOverrides, | ||
| baseDir, | ||
| moduleDirectories, | ||
| modulePaths, | ||
| rootDir, | ||
| ignoreSideEffectsForRoot, | ||
| allowExportsFolderMapping | ||
| }); | ||
| if (exportMapRes) return exportMapRes; | ||
| } catch (error) { | ||
| if (error instanceof ResolveError) { | ||
| warn(error); | ||
| return null; | ||
| } | ||
| throw error; | ||
| } | ||
| return resolveWithClassic({ | ||
| importer, | ||
| importSpecifierList, | ||
| exportConditions, | ||
| warn, | ||
| packageInfoCache, | ||
| extensions, | ||
| mainFields, | ||
| preserveSymlinks, | ||
| useBrowserOverrides, | ||
| baseDir, | ||
| moduleDirectories, | ||
| modulePaths, | ||
| rootDir, | ||
| ignoreSideEffectsForRoot | ||
| }); | ||
| } | ||
| const versionRegexp = /\^(\d+\.\d+\.\d+)/g; | ||
| function validateVersion(actualVersion, peerDependencyVersion) { | ||
| let minMajor = Infinity; | ||
| let minMinor = Infinity; | ||
| let minPatch = Infinity; | ||
| let foundVersion; | ||
| while (foundVersion = versionRegexp.exec(peerDependencyVersion)) { | ||
| const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split(".").map(Number); | ||
| if (foundMajor < minMajor) { | ||
| minMajor = foundMajor; | ||
| minMinor = foundMinor; | ||
| minPatch = foundPatch; | ||
| } | ||
| } | ||
| if (!actualVersion) throw new Error(`Insufficient Rollup version: "@rollup/plugin-node-resolve" requires at least rollup@${minMajor}.${minMinor}.${minPatch}.`); | ||
| const [major, minor, patch] = actualVersion.split(".").map(Number); | ||
| if (major < minMajor || major === minMajor && (minor < minMinor || minor === minMinor && patch < minPatch)) throw new Error(`Insufficient rollup version: "@rollup/plugin-node-resolve" requires at least rollup@${minMajor}.${minMinor}.${minPatch} but found rollup@${actualVersion}.`); | ||
| } | ||
| const ES6_BROWSER_EMPTY = "\0node-resolve:empty.js"; | ||
| const deepFreeze = (object) => { | ||
| Object.freeze(object); | ||
| for (const value of Object.values(object)) if (typeof value === "object" && !Object.isFrozen(value)) deepFreeze(value); | ||
| return object; | ||
| }; | ||
| const baseConditions = ["default", "module"]; | ||
| const baseConditionsEsm = [...baseConditions, "import"]; | ||
| const baseConditionsCjs = [...baseConditions, "require"]; | ||
| const defaults = { | ||
| dedupe: [], | ||
| extensions: [ | ||
| ".mjs", | ||
| ".js", | ||
| ".json", | ||
| ".node" | ||
| ], | ||
| resolveOnly: [], | ||
| moduleDirectories: ["node_modules"], | ||
| modulePaths: [], | ||
| ignoreSideEffectsForRoot: false, | ||
| allowExportsFolderMapping: true | ||
| }; | ||
| const nodeImportPrefix = /^node:/; | ||
| const DEFAULTS = deepFreeze((0, import_cjs.default)({}, defaults)); | ||
| function nodeResolve(opts = {}) { | ||
| const { warnings } = handleDeprecatedOptions(opts); | ||
| const options = { | ||
| ...defaults, | ||
| ...opts | ||
| }; | ||
| const { extensions, jail, moduleDirectories, modulePaths, ignoreSideEffectsForRoot } = options; | ||
| const exportConditions = options.exportConditions || []; | ||
| const devProdCondition = exportConditions.includes("development") || exportConditions.includes("production") ? [] : [process.env.NODE_ENV && process.env.NODE_ENV !== "production" ? "development" : "production"]; | ||
| const conditionsEsm = [ | ||
| ...baseConditionsEsm, | ||
| ...exportConditions, | ||
| ...devProdCondition | ||
| ]; | ||
| const conditionsCjs = [ | ||
| ...baseConditionsCjs, | ||
| ...exportConditions, | ||
| ...devProdCondition | ||
| ]; | ||
| const packageInfoCache = /* @__PURE__ */ new Map(); | ||
| const idToPackageInfo = /* @__PURE__ */ new Map(); | ||
| const mainFields = getMainFields(options); | ||
| const useBrowserOverrides = mainFields.indexOf("browser") !== -1; | ||
| const isPreferBuiltinsSet = Object.prototype.hasOwnProperty.call(options, "preferBuiltins"); | ||
| const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true; | ||
| const rootDir = resolve(options.rootDir || process.cwd()); | ||
| let { dedupe } = options; | ||
| let rollupOptions; | ||
| if (moduleDirectories.some((name) => name.includes("/"))) throw new Error("`moduleDirectories` option must only contain directory names. If you want to load modules from somewhere not supported by the default module resolution algorithm, see `modulePaths`."); | ||
| if (typeof dedupe !== "function") dedupe = (importee) => options.dedupe.includes(importee) || options.dedupe.includes(getPackageName(importee)); | ||
| const allowPatterns = (patterns) => { | ||
| const regexPatterns = patterns.map((pattern) => { | ||
| if (pattern instanceof RegExp) return pattern; | ||
| const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); | ||
| return /* @__PURE__ */ new RegExp(`^${normalized}$`); | ||
| }); | ||
| return (id) => !regexPatterns.length || regexPatterns.some((pattern) => pattern.test(id)); | ||
| }; | ||
| const resolveOnly = typeof options.resolveOnly === "function" ? options.resolveOnly : allowPatterns(options.resolveOnly); | ||
| const browserMapCache = /* @__PURE__ */ new Map(); | ||
| let preserveSymlinks; | ||
| const resolveLikeNode = async (context, importee, importer, custom) => { | ||
| const [importPath, params] = importee.split("?"); | ||
| const importSuffix = `${params ? `?${params}` : ""}`; | ||
| importee = importPath; | ||
| const baseDir = !importer || dedupe(importee) ? rootDir : dirname(importer); | ||
| const browser = browserMapCache.get(importer); | ||
| if (useBrowserOverrides && browser) { | ||
| const resolvedImportee = resolve(baseDir, importee); | ||
| if (browser[importee] === false || browser[resolvedImportee] === false) return { id: ES6_BROWSER_EMPTY }; | ||
| const browserImportee = importee[0] !== "." && browser[importee] || browser[resolvedImportee] || browser[`${resolvedImportee}.js`] || browser[`${resolvedImportee}.json`]; | ||
| if (browserImportee) importee = browserImportee; | ||
| } | ||
| const parts = importee.split(/[/\\]/); | ||
| let id = parts.shift(); | ||
| let isRelativeImport = false; | ||
| if (id[0] === "@" && parts.length > 0) id += `/${parts.shift()}`; | ||
| else if (id[0] === ".") { | ||
| id = resolve(baseDir, importee); | ||
| isRelativeImport = true; | ||
| } | ||
| if (!isRelativeImport && !resolveOnly(id)) { | ||
| if (normalizeInput(rollupOptions.input).includes(importee)) return null; | ||
| return false; | ||
| } | ||
| const importSpecifierList = [importee]; | ||
| if (importer === void 0 && importee[0] && !importee[0].match(/^\.?\.?\//)) importSpecifierList.push(`./${importee}`); | ||
| if (importer && /\.(ts|mts|cts|tsx)$/.test(importer)) { | ||
| for (const [importeeExt, resolvedExt] of [ | ||
| [".js", ".ts"], | ||
| [".js", ".tsx"], | ||
| [".jsx", ".tsx"], | ||
| [".mjs", ".mts"], | ||
| [".cjs", ".cts"] | ||
| ]) if (importee.endsWith(importeeExt) && extensions.includes(resolvedExt)) importSpecifierList.push(importee.slice(0, -importeeExt.length) + resolvedExt); | ||
| } | ||
| const warn = (...args) => context.warn(...args); | ||
| const exportConditions$1 = custom && custom["node-resolve"] && custom["node-resolve"].isRequire ? conditionsCjs : conditionsEsm; | ||
| if (useBrowserOverrides && !exportConditions$1.includes("browser")) exportConditions$1.push("browser"); | ||
| const resolvedWithoutBuiltins = await resolveImportSpecifiers({ | ||
| importer, | ||
| importSpecifierList, | ||
| exportConditions: exportConditions$1, | ||
| warn, | ||
| packageInfoCache, | ||
| extensions, | ||
| mainFields, | ||
| preserveSymlinks, | ||
| useBrowserOverrides, | ||
| baseDir, | ||
| moduleDirectories, | ||
| modulePaths, | ||
| rootDir, | ||
| ignoreSideEffectsForRoot, | ||
| allowExportsFolderMapping: options.allowExportsFolderMapping | ||
| }); | ||
| const importeeIsBuiltin = builtinModules.includes(importee.replace(nodeImportPrefix, "")); | ||
| const preferImporteeIsBuiltin = typeof preferBuiltins === "function" ? preferBuiltins(importee) : preferBuiltins; | ||
| const resolved = importeeIsBuiltin && preferImporteeIsBuiltin ? { | ||
| packageInfo: void 0, | ||
| hasModuleSideEffects: () => null, | ||
| hasPackageEntry: true, | ||
| packageBrowserField: false | ||
| } : resolvedWithoutBuiltins; | ||
| if (!resolved) return null; | ||
| const { packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = resolved; | ||
| let { location } = resolved; | ||
| if (packageBrowserField) { | ||
| if (Object.prototype.hasOwnProperty.call(packageBrowserField, location)) { | ||
| if (!packageBrowserField[location]) { | ||
| browserMapCache.set(location, packageBrowserField); | ||
| return { id: ES6_BROWSER_EMPTY }; | ||
| } | ||
| location = packageBrowserField[location]; | ||
| } | ||
| browserMapCache.set(location, packageBrowserField); | ||
| } | ||
| if (hasPackageEntry && !preserveSymlinks) { | ||
| if (await fileExists(location)) location = await realpath(location); | ||
| } | ||
| idToPackageInfo.set(location, packageInfo); | ||
| if (hasPackageEntry) { | ||
| if (importeeIsBuiltin && preferImporteeIsBuiltin) { | ||
| if (!isPreferBuiltinsSet && resolvedWithoutBuiltins && resolved !== importee) context.warn({ | ||
| message: `preferring built-in module '${importee}' over local alternative at '${resolvedWithoutBuiltins.location}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning.or passing a function to 'preferBuiltins' to provide more fine-grained control over which built-in modules to prefer.`, | ||
| pluginCode: "PREFER_BUILTINS" | ||
| }); | ||
| return false; | ||
| } else if (jail && location.indexOf(normalize(jail.trim(sep))) !== 0) return null; | ||
| } | ||
| if (options.modulesOnly && await fileExists(location)) { | ||
| if ((0, import_is_module.default)(await readFile$1(location, "utf-8"))) return { | ||
| id: `${location}${importSuffix}`, | ||
| moduleSideEffects: hasModuleSideEffects(location) | ||
| }; | ||
| return null; | ||
| } | ||
| return { | ||
| id: `${location}${importSuffix}`, | ||
| moduleSideEffects: hasModuleSideEffects(location) | ||
| }; | ||
| }; | ||
| return { | ||
| name: "node-resolve", | ||
| version, | ||
| buildStart(buildOptions) { | ||
| validateVersion(this.meta.rollupVersion, peerDependencies.rollup); | ||
| rollupOptions = buildOptions; | ||
| for (const warning of warnings) this.warn(warning); | ||
| ({preserveSymlinks} = buildOptions); | ||
| }, | ||
| generateBundle() { | ||
| readCachedFile.clear(); | ||
| isFileCached.clear(); | ||
| isDirCached.clear(); | ||
| }, | ||
| resolveId: { | ||
| order: "post", | ||
| async handler(importee, importer, resolveOptions) { | ||
| if (importee === ES6_BROWSER_EMPTY) return importee; | ||
| if (importee && importee.includes("\0")) return null; | ||
| const { custom = {} } = resolveOptions; | ||
| const { "node-resolve": { resolved: alreadyResolved } = {} } = custom; | ||
| if (alreadyResolved) return alreadyResolved; | ||
| if (importer && importer.includes("\0")) importer = void 0; | ||
| const resolved = await resolveLikeNode(this, importee, importer, custom); | ||
| if (resolved) { | ||
| const resolvedResolved = await this.resolve(resolved.id, importer, { | ||
| ...resolveOptions, | ||
| skipSelf: false, | ||
| custom: { | ||
| ...custom, | ||
| "node-resolve": { | ||
| ...custom["node-resolve"], | ||
| resolved, | ||
| importee | ||
| } | ||
| } | ||
| }); | ||
| if (resolvedResolved) { | ||
| if (resolvedResolved.external) return false; | ||
| if (resolvedResolved.id !== resolved.id) return resolvedResolved; | ||
| return { | ||
| ...resolved, | ||
| meta: resolvedResolved.meta | ||
| }; | ||
| } | ||
| } | ||
| return resolved; | ||
| } | ||
| }, | ||
| load(importee) { | ||
| if (importee === ES6_BROWSER_EMPTY) return "export default {};"; | ||
| return null; | ||
| }, | ||
| getPackageInfoForId(id) { | ||
| return idToPackageInfo.get(id); | ||
| } | ||
| }; | ||
| } | ||
| //#endregion | ||
| export { nodeResolve as t }; |
| import { t as MagicString } from "./magic-string.mjs"; | ||
| import { r as createFilter } from "./plugin-commonjs.mjs"; | ||
| //#region node_modules/.pnpm/@rollup+plugin-replace@6.0.3_rollup@4.53.2/node_modules/@rollup/plugin-replace/dist/es/index.js | ||
| function escape(str) { | ||
| return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&"); | ||
| } | ||
| function ensureFunction(functionOrValue) { | ||
| if (typeof functionOrValue === "function") return functionOrValue; | ||
| return function() { | ||
| return functionOrValue; | ||
| }; | ||
| } | ||
| function longest(a, b) { | ||
| return b.length - a.length; | ||
| } | ||
| function getReplacements(options) { | ||
| if (options.values) return Object.assign({}, options.values); | ||
| var values = Object.assign({}, options); | ||
| delete values.delimiters; | ||
| delete values.include; | ||
| delete values.exclude; | ||
| delete values.sourcemap; | ||
| delete values.sourceMap; | ||
| delete values.objectGuards; | ||
| delete values.preventAssignment; | ||
| return values; | ||
| } | ||
| function mapToFunctions(object) { | ||
| return Object.keys(object).reduce(function(fns, key) { | ||
| var functions = Object.assign({}, fns); | ||
| functions[key] = ensureFunction(object[key]); | ||
| return functions; | ||
| }, {}); | ||
| } | ||
| var objKeyRegEx = /^([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)(\.([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))+$/; | ||
| function expandTypeofReplacements(replacements) { | ||
| Object.keys(replacements).forEach(function(key) { | ||
| var objMatch = key.match(objKeyRegEx); | ||
| if (!objMatch) return; | ||
| var dotIndex = objMatch[1].length; | ||
| do { | ||
| replacements["typeof " + key.slice(0, dotIndex)] = "\"object\""; | ||
| dotIndex = key.indexOf(".", dotIndex + 1); | ||
| } while (dotIndex !== -1); | ||
| }); | ||
| } | ||
| function replace(options) { | ||
| if (options === void 0) options = {}; | ||
| var filter = createFilter(options.include, options.exclude); | ||
| var delimiters = options.delimiters; | ||
| if (delimiters === void 0) delimiters = ["(?<![_$a-zA-Z0-9\\xA0-\\uFFFF])", "(?![_$a-zA-Z0-9\\xA0-\\uFFFF])(?!\\.)"]; | ||
| var preventAssignment = options.preventAssignment; | ||
| var objectGuards = options.objectGuards; | ||
| var replacements = getReplacements(options); | ||
| if (objectGuards) expandTypeofReplacements(replacements); | ||
| var functionValues = mapToFunctions(replacements); | ||
| var keys = Object.keys(functionValues).sort(longest).map(escape); | ||
| var lookbehind = preventAssignment ? "(?<!\\b(?:const|let|var)\\s*)" : ""; | ||
| var lookahead = preventAssignment ? "(?!\\s*=[^=])" : ""; | ||
| var pattern = new RegExp("" + lookbehind + delimiters[0] + "(" + keys.join("|") + ")" + delimiters[1] + lookahead, "g"); | ||
| return { | ||
| name: "replace", | ||
| buildStart: function buildStart() { | ||
| if (![true, false].includes(preventAssignment)) this.warn({ message: "@rollup/plugin-replace: 'preventAssignment' currently defaults to false. It is recommended to set this option to `true`, as the next major version will default this option to `true`." }); | ||
| }, | ||
| renderChunk: function renderChunk(code, chunk) { | ||
| var id = chunk.fileName; | ||
| if (!keys.length) return null; | ||
| if (!filter(id)) return null; | ||
| return executeReplacement(code, id); | ||
| }, | ||
| transform: function transform(code, id) { | ||
| if (!keys.length) return null; | ||
| if (!filter(id)) return null; | ||
| return executeReplacement(code, id); | ||
| } | ||
| }; | ||
| function executeReplacement(code, id) { | ||
| var magicString = new MagicString(code); | ||
| if (!codeHasReplacements(code, id, magicString)) return null; | ||
| var result = { code: magicString.toString() }; | ||
| if (isSourceMapEnabled()) result.map = magicString.generateMap({ hires: true }); | ||
| return result; | ||
| } | ||
| function codeHasReplacements(code, id, magicString) { | ||
| var result = false; | ||
| var match; | ||
| while (match = pattern.exec(code)) { | ||
| result = true; | ||
| var start = match.index; | ||
| var end = start + match[0].length; | ||
| var replacement = String(functionValues[match[1]](id)); | ||
| magicString.overwrite(start, end, replacement); | ||
| } | ||
| return result; | ||
| } | ||
| function isSourceMapEnabled() { | ||
| return options.sourceMap !== false && options.sourcemap !== false; | ||
| } | ||
| } | ||
| //#endregion | ||
| export { replace as t }; |
| //#region node_modules/.pnpm/pretty-bytes@7.1.0/node_modules/pretty-bytes/index.js | ||
| const BYTE_UNITS = [ | ||
| "B", | ||
| "kB", | ||
| "MB", | ||
| "GB", | ||
| "TB", | ||
| "PB", | ||
| "EB", | ||
| "ZB", | ||
| "YB" | ||
| ]; | ||
| const BIBYTE_UNITS = [ | ||
| "B", | ||
| "KiB", | ||
| "MiB", | ||
| "GiB", | ||
| "TiB", | ||
| "PiB", | ||
| "EiB", | ||
| "ZiB", | ||
| "YiB" | ||
| ]; | ||
| const BIT_UNITS = [ | ||
| "b", | ||
| "kbit", | ||
| "Mbit", | ||
| "Gbit", | ||
| "Tbit", | ||
| "Pbit", | ||
| "Ebit", | ||
| "Zbit", | ||
| "Ybit" | ||
| ]; | ||
| const BIBIT_UNITS = [ | ||
| "b", | ||
| "kibit", | ||
| "Mibit", | ||
| "Gibit", | ||
| "Tibit", | ||
| "Pibit", | ||
| "Eibit", | ||
| "Zibit", | ||
| "Yibit" | ||
| ]; | ||
| const toLocaleString = (number, locale, options) => { | ||
| let result = number; | ||
| if (typeof locale === "string" || Array.isArray(locale)) result = number.toLocaleString(locale, options); | ||
| else if (locale === true || options !== void 0) result = number.toLocaleString(void 0, options); | ||
| return result; | ||
| }; | ||
| const log10 = (numberOrBigInt) => { | ||
| if (typeof numberOrBigInt === "number") return Math.log10(numberOrBigInt); | ||
| const string = numberOrBigInt.toString(10); | ||
| return string.length + Math.log10(`0.${string.slice(0, 15)}`); | ||
| }; | ||
| const log = (numberOrBigInt) => { | ||
| if (typeof numberOrBigInt === "number") return Math.log(numberOrBigInt); | ||
| return log10(numberOrBigInt) * Math.log(10); | ||
| }; | ||
| const divide = (numberOrBigInt, divisor) => { | ||
| if (typeof numberOrBigInt === "number") return numberOrBigInt / divisor; | ||
| const integerPart = numberOrBigInt / BigInt(divisor); | ||
| const remainder = numberOrBigInt % BigInt(divisor); | ||
| return Number(integerPart) + Number(remainder) / divisor; | ||
| }; | ||
| const applyFixedWidth = (result, fixedWidth) => { | ||
| if (fixedWidth === void 0) return result; | ||
| if (typeof fixedWidth !== "number" || !Number.isSafeInteger(fixedWidth) || fixedWidth < 0) throw new TypeError(`Expected fixedWidth to be a non-negative integer, got ${typeof fixedWidth}: ${fixedWidth}`); | ||
| if (fixedWidth === 0) return result; | ||
| return result.length < fixedWidth ? result.padStart(fixedWidth, " ") : result; | ||
| }; | ||
| const buildLocaleOptions = (options) => { | ||
| const { minimumFractionDigits, maximumFractionDigits } = options; | ||
| if (minimumFractionDigits === void 0 && maximumFractionDigits === void 0) return; | ||
| return { | ||
| ...minimumFractionDigits !== void 0 && { minimumFractionDigits }, | ||
| ...maximumFractionDigits !== void 0 && { maximumFractionDigits }, | ||
| roundingMode: "trunc" | ||
| }; | ||
| }; | ||
| function prettyBytes(number, options) { | ||
| if (typeof number !== "bigint" && !Number.isFinite(number)) throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`); | ||
| options = { | ||
| bits: false, | ||
| binary: false, | ||
| space: true, | ||
| nonBreakingSpace: false, | ||
| ...options | ||
| }; | ||
| const UNITS = options.bits ? options.binary ? BIBIT_UNITS : BIT_UNITS : options.binary ? BIBYTE_UNITS : BYTE_UNITS; | ||
| const separator = options.space ? options.nonBreakingSpace ? "\xA0" : " " : ""; | ||
| const isZero = typeof number === "number" ? number === 0 : number === 0n; | ||
| if (options.signed && isZero) return applyFixedWidth(` 0${separator}${UNITS[0]}`, options.fixedWidth); | ||
| const isNegative = number < 0; | ||
| const prefix = isNegative ? "-" : options.signed ? "+" : ""; | ||
| if (isNegative) number = -number; | ||
| const localeOptions = buildLocaleOptions(options); | ||
| let result; | ||
| if (number < 1) result = prefix + toLocaleString(number, options.locale, localeOptions) + separator + UNITS[0]; | ||
| else { | ||
| const exponent = Math.min(Math.floor(options.binary ? log(number) / Math.log(1024) : log10(number) / 3), UNITS.length - 1); | ||
| number = divide(number, (options.binary ? 1024 : 1e3) ** exponent); | ||
| if (!localeOptions) { | ||
| const minPrecision = Math.max(3, Math.floor(number).toString().length); | ||
| number = number.toPrecision(minPrecision); | ||
| } | ||
| const numberString = toLocaleString(Number(number), options.locale, localeOptions); | ||
| const unit = UNITS[exponent]; | ||
| result = prefix + numberString + separator + unit; | ||
| } | ||
| return applyFixedWidth(result, options.fixedWidth); | ||
| } | ||
| //#endregion | ||
| export { prettyBytes as t }; |
| //#region node_modules/.pnpm/std-env@3.10.0/node_modules/std-env/dist/index.mjs | ||
| const r = Object.create(null), i = (e) => globalThis.process?.env || import.meta.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (e ? r : globalThis), o = new Proxy(r, { | ||
| get(e, s) { | ||
| return i()[s] ?? r[s]; | ||
| }, | ||
| has(e, s) { | ||
| return s in i() || s in r; | ||
| }, | ||
| set(e, s, E) { | ||
| const B = i(!0); | ||
| return B[s] = E, !0; | ||
| }, | ||
| deleteProperty(e, s) { | ||
| if (!s) return !1; | ||
| const E = i(!0); | ||
| return delete E[s], !0; | ||
| }, | ||
| ownKeys() { | ||
| const e = i(!0); | ||
| return Object.keys(e); | ||
| } | ||
| }), t = typeof process < "u" && process.env && process.env.NODE_ENV || "", f = [ | ||
| ["APPVEYOR"], | ||
| [ | ||
| "AWS_AMPLIFY", | ||
| "AWS_APP_ID", | ||
| { ci: !0 } | ||
| ], | ||
| ["AZURE_PIPELINES", "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"], | ||
| ["AZURE_STATIC", "INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN"], | ||
| ["APPCIRCLE", "AC_APPCIRCLE"], | ||
| ["BAMBOO", "bamboo_planKey"], | ||
| ["BITBUCKET", "BITBUCKET_COMMIT"], | ||
| ["BITRISE", "BITRISE_IO"], | ||
| ["BUDDY", "BUDDY_WORKSPACE_ID"], | ||
| ["BUILDKITE"], | ||
| ["CIRCLE", "CIRCLECI"], | ||
| ["CIRRUS", "CIRRUS_CI"], | ||
| [ | ||
| "CLOUDFLARE_PAGES", | ||
| "CF_PAGES", | ||
| { ci: !0 } | ||
| ], | ||
| [ | ||
| "CLOUDFLARE_WORKERS", | ||
| "WORKERS_CI", | ||
| { ci: !0 } | ||
| ], | ||
| ["CODEBUILD", "CODEBUILD_BUILD_ARN"], | ||
| ["CODEFRESH", "CF_BUILD_ID"], | ||
| ["DRONE"], | ||
| ["DRONE", "DRONE_BUILD_EVENT"], | ||
| ["DSARI"], | ||
| ["GITHUB_ACTIONS"], | ||
| ["GITLAB", "GITLAB_CI"], | ||
| ["GITLAB", "CI_MERGE_REQUEST_ID"], | ||
| ["GOCD", "GO_PIPELINE_LABEL"], | ||
| ["LAYERCI"], | ||
| ["HUDSON", "HUDSON_URL"], | ||
| ["JENKINS", "JENKINS_URL"], | ||
| ["MAGNUM"], | ||
| ["NETLIFY"], | ||
| [ | ||
| "NETLIFY", | ||
| "NETLIFY_LOCAL", | ||
| { ci: !1 } | ||
| ], | ||
| ["NEVERCODE"], | ||
| ["RENDER"], | ||
| ["SAIL", "SAILCI"], | ||
| ["SEMAPHORE"], | ||
| ["SCREWDRIVER"], | ||
| ["SHIPPABLE"], | ||
| ["SOLANO", "TDDIUM"], | ||
| ["STRIDER"], | ||
| ["TEAMCITY", "TEAMCITY_VERSION"], | ||
| ["TRAVIS"], | ||
| ["VERCEL", "NOW_BUILDER"], | ||
| [ | ||
| "VERCEL", | ||
| "VERCEL", | ||
| { ci: !1 } | ||
| ], | ||
| [ | ||
| "VERCEL", | ||
| "VERCEL_ENV", | ||
| { ci: !1 } | ||
| ], | ||
| ["APPCENTER", "APPCENTER_BUILD_ID"], | ||
| [ | ||
| "CODESANDBOX", | ||
| "CODESANDBOX_SSE", | ||
| { ci: !1 } | ||
| ], | ||
| [ | ||
| "CODESANDBOX", | ||
| "CODESANDBOX_HOST", | ||
| { ci: !1 } | ||
| ], | ||
| ["STACKBLITZ"], | ||
| ["STORMKIT"], | ||
| ["CLEAVR"], | ||
| ["ZEABUR"], | ||
| [ | ||
| "CODESPHERE", | ||
| "CODESPHERE_APP_ID", | ||
| { ci: !0 } | ||
| ], | ||
| ["RAILWAY", "RAILWAY_PROJECT_ID"], | ||
| ["RAILWAY", "RAILWAY_SERVICE_ID"], | ||
| ["DENO-DEPLOY", "DENO_DEPLOYMENT_ID"], | ||
| [ | ||
| "FIREBASE_APP_HOSTING", | ||
| "FIREBASE_APP_HOSTING", | ||
| { ci: !0 } | ||
| ] | ||
| ]; | ||
| function b() { | ||
| if (globalThis.process?.env) for (const e of f) { | ||
| const s = e[1] || e[0]; | ||
| if (globalThis.process?.env[s]) return { | ||
| name: e[0].toLowerCase(), | ||
| ...e[2] | ||
| }; | ||
| } | ||
| return globalThis.process?.env?.SHELL === "/bin/jsh" && globalThis.process?.versions?.webcontainer ? { | ||
| name: "stackblitz", | ||
| ci: !1 | ||
| } : { | ||
| name: "", | ||
| ci: !1 | ||
| }; | ||
| } | ||
| const l = b(), p = l.name; | ||
| function n(e) { | ||
| return e ? e !== "false" : !1; | ||
| } | ||
| const I = globalThis.process?.platform || "", T = n(o.CI) || l.ci !== !1, R = n(globalThis.process?.stdout && globalThis.process?.stdout.isTTY), U = typeof window < "u", d = n(o.DEBUG), a = t === "test" || n(o.TEST), g = t === "production", h = t === "dev" || t === "development", v = n(o.MINIMAL) || T || a || !R, A = /^win/i.test(I), M = /^linux/i.test(I), m = /^darwin/i.test(I), Y = !n(o.NO_COLOR) && (n(o.FORCE_COLOR) || (R || A) && o.TERM !== "dumb" || T), C = (globalThis.process?.versions?.node || "").replace(/^v/, "") || null, V = Number(C?.split(".")[0]) || null, W = globalThis.process || Object.create(null), _ = { versions: {} }, y = new Proxy(W, { get(e, s) { | ||
| if (s === "env") return o; | ||
| if (s in e) return e[s]; | ||
| if (s in _) return _[s]; | ||
| } }), O = globalThis.process?.release?.name === "node", c = !!globalThis.Bun || !!globalThis.process?.versions?.bun, D = !!globalThis.Deno, L = !!globalThis.fastly, S = !!globalThis.Netlify, u = !!globalThis.EdgeRuntime, N = globalThis.navigator?.userAgent === "Cloudflare-Workers", F = [ | ||
| [S, "netlify"], | ||
| [u, "edge-light"], | ||
| [N, "workerd"], | ||
| [L, "fastly"], | ||
| [D, "deno"], | ||
| [c, "bun"], | ||
| [O, "node"] | ||
| ]; | ||
| function G() { | ||
| const e = F.find((s) => s[0]); | ||
| if (e) return { name: e[1] }; | ||
| } | ||
| const P = G(), K = P?.name || ""; | ||
| //#endregion | ||
| export { p as a, d as i, T as n, a as r, K as t }; |
| import { i as __toESM } from "../_chunks/Bqks5huO.mjs"; | ||
| import { t as require_js_tokens } from "./js-tokens.mjs"; | ||
| //#region node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.mjs | ||
| var import_js_tokens = /* @__PURE__ */ __toESM(require_js_tokens(), 1); | ||
| const FILL_COMMENT = " "; | ||
| function stripLiteralFromToken(token, fillChar, filter) { | ||
| if (token.type === "SingleLineComment") return FILL_COMMENT.repeat(token.value.length); | ||
| if (token.type === "MultiLineComment") return token.value.replace(/[^\n]/g, FILL_COMMENT); | ||
| if (token.type === "StringLiteral") { | ||
| if (!token.closed) return token.value; | ||
| const body = token.value.slice(1, -1); | ||
| if (filter(body)) return token.value[0] + fillChar.repeat(body.length) + token.value[token.value.length - 1]; | ||
| } | ||
| if (token.type === "NoSubstitutionTemplate") { | ||
| const body = token.value.slice(1, -1); | ||
| if (filter(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\``; | ||
| } | ||
| if (token.type === "RegularExpressionLiteral") { | ||
| const body = token.value; | ||
| if (filter(body)) return body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${fillChar.repeat($1.length)}/${$2}`); | ||
| } | ||
| if (token.type === "TemplateHead") { | ||
| const body = token.value.slice(1, -2); | ||
| if (filter(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\${`; | ||
| } | ||
| if (token.type === "TemplateTail") { | ||
| const body = token.value.slice(0, -2); | ||
| if (filter(body)) return `}${body.replace(/[^\n]/g, fillChar)}\``; | ||
| } | ||
| if (token.type === "TemplateMiddle") { | ||
| const body = token.value.slice(1, -2); | ||
| if (filter(body)) return `}${body.replace(/[^\n]/g, fillChar)}\${`; | ||
| } | ||
| return token.value; | ||
| } | ||
| function optionsWithDefaults(options) { | ||
| return { | ||
| fillChar: options?.fillChar ?? " ", | ||
| filter: options?.filter ?? (() => true) | ||
| }; | ||
| } | ||
| function stripLiteral(code, options) { | ||
| let result = ""; | ||
| const _options = optionsWithDefaults(options); | ||
| for (const token of (0, import_js_tokens.default)(code, { jsx: false })) result += stripLiteralFromToken(token, _options.fillChar, _options.filter); | ||
| return result; | ||
| } | ||
| //#endregion | ||
| export { stripLiteral as t }; |
| import { i as __toESM } from "../_chunks/Bqks5huO.mjs"; | ||
| import { t as require_picomatch } from "./picomatch.mjs"; | ||
| import { t as Builder } from "./fdir.mjs"; | ||
| import nativeFs from "fs"; | ||
| import path, { posix } from "path"; | ||
| import { fileURLToPath } from "url"; | ||
| //#region node_modules/.pnpm/tinyglobby@0.2.15/node_modules/tinyglobby/dist/index.mjs | ||
| var import_picomatch = /* @__PURE__ */ __toESM(require_picomatch(), 1); | ||
| const isReadonlyArray = Array.isArray; | ||
| const isWin = process.platform === "win32"; | ||
| const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/; | ||
| function getPartialMatcher(patterns, options = {}) { | ||
| const patternsCount = patterns.length; | ||
| const patternsParts = Array(patternsCount); | ||
| const matchers = Array(patternsCount); | ||
| const globstarEnabled = !options.noglobstar; | ||
| for (let i = 0; i < patternsCount; i++) { | ||
| const parts = splitPattern(patterns[i]); | ||
| patternsParts[i] = parts; | ||
| const partsCount = parts.length; | ||
| const partMatchers = Array(partsCount); | ||
| for (let j = 0; j < partsCount; j++) partMatchers[j] = (0, import_picomatch.default)(parts[j], options); | ||
| matchers[i] = partMatchers; | ||
| } | ||
| return (input) => { | ||
| const inputParts = input.split("/"); | ||
| if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true; | ||
| for (let i = 0; i < patterns.length; i++) { | ||
| const patternParts = patternsParts[i]; | ||
| const matcher = matchers[i]; | ||
| const inputPatternCount = inputParts.length; | ||
| const minParts = Math.min(inputPatternCount, patternParts.length); | ||
| let j = 0; | ||
| while (j < minParts) { | ||
| const part = patternParts[j]; | ||
| if (part.includes("/")) return true; | ||
| if (!matcher[j](inputParts[j])) break; | ||
| if (globstarEnabled && part === "**") return true; | ||
| j++; | ||
| } | ||
| if (j === inputPatternCount) return true; | ||
| } | ||
| return false; | ||
| }; | ||
| } | ||
| /* node:coverage ignore next 2 */ | ||
| const WIN32_ROOT_DIR = /^[A-Z]:\/$/i; | ||
| const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/"; | ||
| function buildFormat(cwd, root, absolute) { | ||
| if (cwd === root || root.startsWith(`${cwd}/`)) { | ||
| if (absolute) { | ||
| const start = isRoot(cwd) ? cwd.length : cwd.length + 1; | ||
| return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || "."; | ||
| } | ||
| const prefix = root.slice(cwd.length + 1); | ||
| if (prefix) return (p, isDir) => { | ||
| if (p === ".") return prefix; | ||
| const result = `${prefix}/${p}`; | ||
| return isDir ? result.slice(0, -1) : result; | ||
| }; | ||
| return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p; | ||
| } | ||
| if (absolute) return (p) => posix.relative(cwd, p) || "."; | ||
| return (p) => posix.relative(cwd, `${root}/${p}`) || "."; | ||
| } | ||
| function buildRelative(cwd, root) { | ||
| if (root.startsWith(`${cwd}/`)) { | ||
| const prefix = root.slice(cwd.length + 1); | ||
| return (p) => `${prefix}/${p}`; | ||
| } | ||
| return (p) => { | ||
| const result = posix.relative(cwd, `${root}/${p}`); | ||
| if (p.endsWith("/") && result !== "") return `${result}/`; | ||
| return result || "."; | ||
| }; | ||
| } | ||
| const splitPatternOptions = { parts: true }; | ||
| function splitPattern(path$1) { | ||
| var _result$parts; | ||
| const result = import_picomatch.default.scan(path$1, splitPatternOptions); | ||
| return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path$1]; | ||
| } | ||
| const POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g; | ||
| const WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g; | ||
| const escapePosixPath = (path$1) => path$1.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&"); | ||
| const escapeWin32Path = (path$1) => path$1.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&"); | ||
| /** | ||
| * Escapes a path's special characters depending on the platform. | ||
| * @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath} | ||
| */ | ||
| /* node:coverage ignore next */ | ||
| const escapePath = isWin ? escapeWin32Path : escapePosixPath; | ||
| /** | ||
| * Checks if a pattern has dynamic parts. | ||
| * | ||
| * Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy: | ||
| * | ||
| * - Doesn't necessarily return `false` on patterns that include `\`. | ||
| * - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not. | ||
| * - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`. | ||
| * - Returns `true` for unfinished brace expansions as long as they include `,` or `..`. | ||
| * | ||
| * @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern} | ||
| */ | ||
| function isDynamicPattern(pattern, options) { | ||
| if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true; | ||
| const scan = import_picomatch.default.scan(pattern); | ||
| return scan.isGlob || scan.negated; | ||
| } | ||
| function log(...tasks) { | ||
| console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks); | ||
| } | ||
| const PARENT_DIRECTORY = /^(\/?\.\.)+/; | ||
| const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g; | ||
| const BACKSLASHES = /\\/g; | ||
| function normalizePattern(pattern, expandDirectories, cwd, props, isIgnore) { | ||
| let result = pattern; | ||
| if (pattern.endsWith("/")) result = pattern.slice(0, -1); | ||
| if (!result.endsWith("*") && expandDirectories) result += "/**"; | ||
| const escapedCwd = escapePath(cwd); | ||
| if (path.isAbsolute(result.replace(ESCAPING_BACKSLASHES, ""))) result = posix.relative(escapedCwd, result); | ||
| else result = posix.normalize(result); | ||
| const parentDirectoryMatch = PARENT_DIRECTORY.exec(result); | ||
| const parts = splitPattern(result); | ||
| if (parentDirectoryMatch === null || parentDirectoryMatch === void 0 ? void 0 : parentDirectoryMatch[0]) { | ||
| const n = (parentDirectoryMatch[0].length + 1) / 3; | ||
| let i = 0; | ||
| const cwdParts = escapedCwd.split("/"); | ||
| while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) { | ||
| result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || "."; | ||
| i++; | ||
| } | ||
| const potentialRoot = posix.join(cwd, parentDirectoryMatch[0].slice(i * 3)); | ||
| if (!potentialRoot.startsWith(".") && props.root.length > potentialRoot.length) { | ||
| props.root = potentialRoot; | ||
| props.depthOffset = -n + i; | ||
| } | ||
| } | ||
| if (!isIgnore && props.depthOffset >= 0) { | ||
| var _props$commonPath; | ||
| (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts); | ||
| const newCommonPath = []; | ||
| const length = Math.min(props.commonPath.length, parts.length); | ||
| for (let i = 0; i < length; i++) { | ||
| const part = parts[i]; | ||
| if (part === "**" && !parts[i + 1]) { | ||
| newCommonPath.pop(); | ||
| break; | ||
| } | ||
| if (part !== props.commonPath[i] || isDynamicPattern(part) || i === parts.length - 1) break; | ||
| newCommonPath.push(part); | ||
| } | ||
| props.depthOffset = newCommonPath.length; | ||
| props.commonPath = newCommonPath; | ||
| props.root = newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd; | ||
| } | ||
| return result; | ||
| } | ||
| function processPatterns({ patterns = ["**/*"], ignore = [], expandDirectories = true }, cwd, props) { | ||
| if (typeof patterns === "string") patterns = [patterns]; | ||
| if (typeof ignore === "string") ignore = [ignore]; | ||
| const matchPatterns = []; | ||
| const ignorePatterns = []; | ||
| for (const pattern of ignore) { | ||
| if (!pattern) continue; | ||
| if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, true)); | ||
| } | ||
| for (const pattern of patterns) { | ||
| if (!pattern) continue; | ||
| if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, false)); | ||
| else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), expandDirectories, cwd, props, true)); | ||
| } | ||
| return { | ||
| match: matchPatterns, | ||
| ignore: ignorePatterns | ||
| }; | ||
| } | ||
| function formatPaths(paths, relative$1) { | ||
| for (let i = paths.length - 1; i >= 0; i--) { | ||
| const path$1 = paths[i]; | ||
| paths[i] = relative$1(path$1); | ||
| } | ||
| return paths; | ||
| } | ||
| function normalizeCwd(cwd) { | ||
| if (!cwd) return process.cwd().replace(BACKSLASHES, "/"); | ||
| if (cwd instanceof URL) return fileURLToPath(cwd).replace(BACKSLASHES, "/"); | ||
| return path.resolve(cwd).replace(BACKSLASHES, "/"); | ||
| } | ||
| function getCrawler(patterns, inputOptions = {}) { | ||
| const options = process.env.TINYGLOBBY_DEBUG ? { | ||
| ...inputOptions, | ||
| debug: true | ||
| } : inputOptions; | ||
| const cwd = normalizeCwd(options.cwd); | ||
| if (options.debug) log("globbing with:", { | ||
| patterns, | ||
| options, | ||
| cwd | ||
| }); | ||
| if (Array.isArray(patterns) && patterns.length === 0) return [{ | ||
| sync: () => [], | ||
| withPromise: async () => [] | ||
| }, false]; | ||
| const props = { | ||
| root: cwd, | ||
| commonPath: null, | ||
| depthOffset: 0 | ||
| }; | ||
| const processed = processPatterns({ | ||
| ...options, | ||
| patterns | ||
| }, cwd, props); | ||
| if (options.debug) log("internal processing patterns:", processed); | ||
| const matchOptions = { | ||
| dot: options.dot, | ||
| nobrace: options.braceExpansion === false, | ||
| nocase: options.caseSensitiveMatch === false, | ||
| noextglob: options.extglob === false, | ||
| noglobstar: options.globstar === false, | ||
| posix: true | ||
| }; | ||
| const matcher = (0, import_picomatch.default)(processed.match, { | ||
| ...matchOptions, | ||
| ignore: processed.ignore | ||
| }); | ||
| const ignore = (0, import_picomatch.default)(processed.ignore, matchOptions); | ||
| const partialMatcher = getPartialMatcher(processed.match, matchOptions); | ||
| const format = buildFormat(cwd, props.root, options.absolute); | ||
| const formatExclude = options.absolute ? format : buildFormat(cwd, props.root, true); | ||
| const fdirOptions = { | ||
| filters: [options.debug ? (p, isDirectory) => { | ||
| const path$1 = format(p, isDirectory); | ||
| const matches = matcher(path$1); | ||
| if (matches) log(`matched ${path$1}`); | ||
| return matches; | ||
| } : (p, isDirectory) => matcher(format(p, isDirectory))], | ||
| exclude: options.debug ? (_, p) => { | ||
| const relativePath = formatExclude(p, true); | ||
| const skipped = relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath); | ||
| if (skipped) log(`skipped ${p}`); | ||
| else log(`crawling ${p}`); | ||
| return skipped; | ||
| } : (_, p) => { | ||
| const relativePath = formatExclude(p, true); | ||
| return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath); | ||
| }, | ||
| fs: options.fs ? { | ||
| readdir: options.fs.readdir || nativeFs.readdir, | ||
| readdirSync: options.fs.readdirSync || nativeFs.readdirSync, | ||
| realpath: options.fs.realpath || nativeFs.realpath, | ||
| realpathSync: options.fs.realpathSync || nativeFs.realpathSync, | ||
| stat: options.fs.stat || nativeFs.stat, | ||
| statSync: options.fs.statSync || nativeFs.statSync | ||
| } : void 0, | ||
| pathSeparator: "/", | ||
| relativePaths: true, | ||
| resolveSymlinks: true, | ||
| signal: options.signal | ||
| }; | ||
| if (options.deep !== void 0) fdirOptions.maxDepth = Math.round(options.deep - props.depthOffset); | ||
| if (options.absolute) { | ||
| fdirOptions.relativePaths = false; | ||
| fdirOptions.resolvePaths = true; | ||
| fdirOptions.includeBasePath = true; | ||
| } | ||
| if (options.followSymbolicLinks === false) { | ||
| fdirOptions.resolveSymlinks = false; | ||
| fdirOptions.excludeSymlinks = true; | ||
| } | ||
| if (options.onlyDirectories) { | ||
| fdirOptions.excludeFiles = true; | ||
| fdirOptions.includeDirs = true; | ||
| } else if (options.onlyFiles === false) fdirOptions.includeDirs = true; | ||
| props.root = props.root.replace(BACKSLASHES, ""); | ||
| const root = props.root; | ||
| if (options.debug) log("internal properties:", props); | ||
| const relative$1 = cwd !== root && !options.absolute && buildRelative(cwd, props.root); | ||
| return [new Builder(fdirOptions).crawl(root), relative$1]; | ||
| } | ||
| async function glob(patternsOrOptions, options) { | ||
| if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option"); | ||
| const isModern = isReadonlyArray(patternsOrOptions) || typeof patternsOrOptions === "string"; | ||
| const opts = isModern ? options : patternsOrOptions; | ||
| const [crawler, relative$1] = getCrawler(isModern ? patternsOrOptions : patternsOrOptions.patterns, opts); | ||
| if (!relative$1) return crawler.withPromise(); | ||
| return formatPaths(await crawler.withPromise(), relative$1); | ||
| } | ||
| //#endregion | ||
| export { glob as t }; |
Sorry, the diff of this file is too big to display
| import { r as genObjectKey } from "./knitwork.mjs"; | ||
| import "scule"; | ||
| //#region node_modules/.pnpm/untyped@2.0.0/node_modules/untyped/dist/shared/untyped.Br_uXjZG.mjs | ||
| function getType(val) { | ||
| const type = typeof val; | ||
| if (type === "undefined" || val === null) return; | ||
| if (Array.isArray(val)) return "array"; | ||
| return type; | ||
| } | ||
| function isObject(val) { | ||
| return val !== null && !Array.isArray(val) && typeof val === "object"; | ||
| } | ||
| function nonEmpty(arr) { | ||
| return arr.filter(Boolean); | ||
| } | ||
| function unique(arr) { | ||
| return [...new Set(arr)]; | ||
| } | ||
| function joinPath(a, b = "", sep = ".") { | ||
| return a ? a + sep + b : b; | ||
| } | ||
| function setValue(obj, path, val) { | ||
| const keys = path.split("."); | ||
| const _key = keys.pop(); | ||
| for (const key of keys) { | ||
| if (!obj || typeof obj !== "object") return; | ||
| if (!(key in obj)) obj[key] = {}; | ||
| obj = obj[key]; | ||
| } | ||
| if (_key) { | ||
| if (!obj || typeof obj !== "object") return; | ||
| obj[_key] = val; | ||
| } | ||
| } | ||
| function getValue(obj, path) { | ||
| for (const key of path.split(".")) { | ||
| if (!obj || typeof obj !== "object" || !(key in obj)) return; | ||
| obj = obj[key]; | ||
| } | ||
| return obj; | ||
| } | ||
| function normalizeTypes(val) { | ||
| const arr = unique(val.filter(Boolean)); | ||
| if (arr.length === 0 || arr.includes("any")) return; | ||
| return arr.length > 1 ? arr : arr[0]; | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/untyped@2.0.0/node_modules/untyped/dist/shared/untyped.BTwOq8Jl.mjs | ||
| async function resolveSchema(obj, defaults, options = {}) { | ||
| return await _resolveSchema(obj, "", { | ||
| root: obj, | ||
| defaults, | ||
| resolveCache: {}, | ||
| ignoreDefaults: !!options.ignoreDefaults | ||
| }); | ||
| } | ||
| async function _resolveSchema(input, id, ctx) { | ||
| if (id in ctx.resolveCache) return ctx.resolveCache[id]; | ||
| const schemaId = "#" + id.replace(/\./g, "/"); | ||
| if (!isObject(input)) { | ||
| const safeInput = Array.isArray(input) ? [...input] : input; | ||
| const schema2 = { | ||
| type: getType(input), | ||
| id: schemaId, | ||
| default: ctx.ignoreDefaults ? void 0 : safeInput | ||
| }; | ||
| normalizeSchema(schema2, { ignoreDefaults: ctx.ignoreDefaults }); | ||
| ctx.resolveCache[id] = schema2; | ||
| if (ctx.defaults && getValue(ctx.defaults, id) === void 0) setValue(ctx.defaults, id, schema2.default); | ||
| return schema2; | ||
| } | ||
| const node = { ...input }; | ||
| const schema = ctx.resolveCache[id] = { | ||
| ...node.$schema, | ||
| id: schemaId | ||
| }; | ||
| for (const key in node) { | ||
| if (key === "$resolve" || key === "$schema" || key === "$default") continue; | ||
| schema.properties = schema.properties || {}; | ||
| if (!schema.properties[key]) { | ||
| const child = schema.properties[key] = await _resolveSchema(node[key], joinPath(id, key), ctx); | ||
| if (Array.isArray(child.tags) && child.tags.includes("@required")) { | ||
| schema.required = schema.required || []; | ||
| if (!schema.required.includes(key)) schema.required.push(key); | ||
| } | ||
| } | ||
| } | ||
| if (!ctx.ignoreDefaults) { | ||
| if (ctx.defaults) schema.default = getValue(ctx.defaults, id); | ||
| if (schema.default === void 0 && "$default" in node) schema.default = node.$default; | ||
| if (typeof node.$resolve === "function") schema.default = await node.$resolve(schema.default, async (key) => { | ||
| return (await _resolveSchema(getValue(ctx.root, key), key, ctx)).default; | ||
| }); | ||
| } | ||
| if (ctx.defaults) setValue(ctx.defaults, id, schema.default); | ||
| if (!schema.type) schema.type = getType(schema.default) || (schema.properties ? "object" : "any"); | ||
| normalizeSchema(schema, { ignoreDefaults: ctx.ignoreDefaults }); | ||
| if (ctx.defaults && getValue(ctx.defaults, id) === void 0) setValue(ctx.defaults, id, schema.default); | ||
| return schema; | ||
| } | ||
| function normalizeSchema(schema, options) { | ||
| if (schema.type === "array" && !("items" in schema)) { | ||
| schema.items = { type: nonEmpty(unique(schema.default.map((i) => getType(i)))) }; | ||
| if (schema.items.type) { | ||
| if (schema.items.type.length === 0) schema.items.type = "any"; | ||
| else if (schema.items.type.length === 1) schema.items.type = schema.items.type[0]; | ||
| } | ||
| } | ||
| if (!options.ignoreDefaults && schema.default === void 0 && ("properties" in schema || schema.type === "object" || schema.type === "any")) { | ||
| const propsWithDefaults = Object.entries(schema.properties || {}).filter(([, prop]) => "default" in prop).map(([key, value]) => [key, value.default]); | ||
| schema.default = Object.fromEntries(propsWithDefaults); | ||
| } | ||
| } | ||
| //#endregion | ||
| //#region node_modules/.pnpm/untyped@2.0.0/node_modules/untyped/dist/index.mjs | ||
| const GenerateTypesDefaults = { | ||
| interfaceName: "Untyped", | ||
| addExport: true, | ||
| addDefaults: true, | ||
| allowExtraKeys: void 0, | ||
| partial: false, | ||
| indentation: 0 | ||
| }; | ||
| const TYPE_MAP = { | ||
| array: "any[]", | ||
| bigint: "bigint", | ||
| boolean: "boolean", | ||
| number: "number", | ||
| object: "", | ||
| any: "any", | ||
| string: "string", | ||
| symbol: "Symbol", | ||
| function: "Function" | ||
| }; | ||
| const SCHEMA_KEYS = /* @__PURE__ */ new Set([ | ||
| "items", | ||
| "default", | ||
| "resolve", | ||
| "properties", | ||
| "title", | ||
| "description", | ||
| "$schema", | ||
| "type", | ||
| "tsType", | ||
| "markdownType", | ||
| "tags", | ||
| "args", | ||
| "id", | ||
| "returns" | ||
| ]); | ||
| const DECLARATION_RE = /typeof import\(["'](?<source>[^)]+)["']\)(\.(?<type>\w+)|\[["'](?<type1>\w+)["']])/g; | ||
| function extractTypeImports(declarations) { | ||
| const typeImports = {}; | ||
| const aliases = /* @__PURE__ */ new Set(); | ||
| const imports = []; | ||
| for (const match of declarations.matchAll(DECLARATION_RE)) { | ||
| const { source, type1, type = type1 } = match.groups || {}; | ||
| typeImports[source] = typeImports[source] || /* @__PURE__ */ new Set(); | ||
| typeImports[source].add(type); | ||
| } | ||
| for (const source in typeImports) { | ||
| const sourceImports = []; | ||
| for (const type of typeImports[source]) { | ||
| let count = 0; | ||
| let alias = type; | ||
| while (aliases.has(alias)) alias = `${type}${count++}`; | ||
| aliases.add(alias); | ||
| sourceImports.push(alias === type ? type : `${type} as ${alias}`); | ||
| declarations = declarations.replace(new RegExp(`typeof import\\(['"]${source}['"]\\)(\\.${type}|\\[['"]${type}['"]\\])`, "g"), alias); | ||
| } | ||
| imports.push(`import type { ${sourceImports.join(", ")} } from '${source}'`); | ||
| } | ||
| return [...imports, declarations].join("\n"); | ||
| } | ||
| function generateTypes(schema, opts = {}) { | ||
| opts = { | ||
| ...GenerateTypesDefaults, | ||
| ...opts | ||
| }; | ||
| const baseIden = " ".repeat(opts.indentation || 0); | ||
| const interfaceCode = `interface ${opts.interfaceName} { | ||
| ` + _genTypes(schema, baseIden + " ", opts).map((l) => l.trim().length > 0 ? l : "").join("\n") + ` | ||
| ${baseIden}}`; | ||
| if (!opts.addExport) return baseIden + interfaceCode; | ||
| return extractTypeImports(baseIden + `export ${interfaceCode}`); | ||
| } | ||
| function _genTypes(schema, spaces, opts) { | ||
| const buff = []; | ||
| if (!schema) return buff; | ||
| for (const key in schema.properties) { | ||
| const val = schema.properties[key]; | ||
| buff.push(...generateJSDoc(val, opts)); | ||
| if (val.tsType) buff.push(`${genObjectKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: ${val.tsType}, | ||
| `); | ||
| else if (val.type === "object") buff.push(`${genObjectKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: {`, ..._genTypes(val, spaces, opts), "},\n"); | ||
| else { | ||
| let type; | ||
| if (val.type === "array") type = `Array<${getTsType(val.items || [], opts)}>`; | ||
| else if (val.type === "function") type = genFunctionType(val, opts); | ||
| else type = getTsType(val, opts); | ||
| buff.push(`${genObjectKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: ${type}, | ||
| `); | ||
| } | ||
| } | ||
| if (buff.length > 0) { | ||
| const last = buff.pop() || ""; | ||
| buff.push(last.slice(0, Math.max(0, last.length - 1))); | ||
| } | ||
| if (opts.allowExtraKeys === true || buff.length === 0 && opts.allowExtraKeys !== false) buff.push("[key: string]: any"); | ||
| return buff.flatMap((l) => l.split("\n")).map((l) => spaces + l); | ||
| } | ||
| function getTsType(type, opts) { | ||
| if (Array.isArray(type)) return [normalizeTypes(type.map((t) => getTsType(t, opts)))].flat().join("|") || "any"; | ||
| if (!type) return "any"; | ||
| if (type.tsType) return type.tsType; | ||
| if (!type.type) return "any"; | ||
| if (Array.isArray(type.type)) return type.type.map((t) => { | ||
| if (t === "object" && type.type.length > 1) return `{ | ||
| ` + _genTypes(type, " ", opts).join("\n") + ` | ||
| }`; | ||
| return TYPE_MAP[t]; | ||
| }).join("|"); | ||
| if (type.type === "array") return `Array<${getTsType(type.items || [], opts)}>`; | ||
| if (type.type === "object") return `{ | ||
| ` + _genTypes(type, " ", opts).join("\n") + ` | ||
| }`; | ||
| return TYPE_MAP[type.type] || type.type; | ||
| } | ||
| function genFunctionType(schema, opts) { | ||
| return `(${genFunctionArgs(schema.args, opts)}) => ${getTsType(schema.returns || [], opts)}`; | ||
| } | ||
| function genFunctionArgs(args, opts) { | ||
| return args?.map((arg) => { | ||
| let argStr = arg.name; | ||
| if (arg.optional || arg.default) argStr += "?"; | ||
| if (arg.type || arg.tsType) argStr += `: ${getTsType(arg, opts)}`; | ||
| return argStr; | ||
| }).join(", ") || ""; | ||
| } | ||
| function generateJSDoc(schema, opts) { | ||
| opts.defaultDescription = opts.defaultDescription || opts.defaultDescrption; | ||
| let buff = []; | ||
| if (schema.title) buff.push(schema.title, ""); | ||
| if (schema.description) buff.push(schema.description, ""); | ||
| else if (opts.defaultDescription && schema.type !== "object") buff.push(opts.defaultDescription, ""); | ||
| if (opts.addDefaults && schema.type !== "object" && schema.type !== "any" && !(Array.isArray(schema.default) && schema.default.length === 0)) { | ||
| const stringified = JSON.stringify(schema.default); | ||
| if (stringified) buff.push(`@default ${stringified.replace(/\*\//g, String.raw`*\/`)}`); | ||
| } | ||
| for (const key in schema) if (!SCHEMA_KEYS.has(key)) buff.push("", `@${key} ${schema[key]}`); | ||
| if (Array.isArray(schema.tags)) { | ||
| for (const tag of schema.tags) if (tag !== "@untyped") buff.push("", tag); | ||
| } | ||
| buff = buff.flatMap((i) => i.split("\n")); | ||
| if (buff.length > 0) return buff.length === 1 ? ["/** " + buff[0] + " */"] : [ | ||
| "/**", | ||
| ...buff.map((i) => ` * ${i}`), | ||
| "*/" | ||
| ]; | ||
| return []; | ||
| } | ||
| function isRequired(schema, key, opts) { | ||
| if (Array.isArray(schema.required) && schema.required.includes(key)) return true; | ||
| return !opts.partial; | ||
| } | ||
| //#endregion | ||
| export { resolveSchema as n, generateTypes as t }; |
Sorry, the diff of this file is too big to display
| import { t as MagicString } from "./magic-string.mjs"; | ||
| import { t as stripLiteral } from "./strip-literal.mjs"; | ||
| import path from "node:path"; | ||
| import fs from "node:fs"; | ||
| import { fileURLToPath } from "node:url"; | ||
| import assert from "node:assert"; | ||
| import "srvx/node"; | ||
| import { createHash } from "node:crypto"; | ||
| import { isCSSRequest, normalizePath } from "vite"; | ||
| import assert$1 from "node:assert/strict"; | ||
| //#region node_modules/.pnpm/@pi0+vite-plugin-fullstack@0.0.5-pr-1297_vite@7.2.2_@types+node@24.10.0_jiti@2.6.1_ligh_420de11c17db6dc1bb00fb6cc17e9a42/node_modules/@pi0/vite-plugin-fullstack/dist/index.js | ||
| function parseIdQuery(id) { | ||
| if (!id.includes("?")) return { | ||
| filename: id, | ||
| query: {} | ||
| }; | ||
| const [filename, rawQuery] = id.split(`?`, 2); | ||
| return { | ||
| filename, | ||
| query: Object.fromEntries(new URLSearchParams(rawQuery)) | ||
| }; | ||
| } | ||
| function toAssetsVirtual(options) { | ||
| return `virtual:fullstack/assets?${new URLSearchParams(options)}&lang.js`; | ||
| } | ||
| function parseAssetsVirtual(id) { | ||
| if (id.startsWith("\0virtual:fullstack/assets?")) return parseIdQuery(id).query; | ||
| } | ||
| function createVirtualPlugin(name, load) { | ||
| name = "virtual:" + name; | ||
| return { | ||
| name: `rsc:virtual-${name}`, | ||
| resolveId: { handler(source, _importer, _options) { | ||
| return source === name ? "\0" + name : void 0; | ||
| } }, | ||
| load: { handler(id, options) { | ||
| if (id === "\0" + name) return load.apply(this, [id, options]); | ||
| } } | ||
| }; | ||
| } | ||
| function normalizeRelativePath(s) { | ||
| s = normalizePath(s); | ||
| return s[0] === "." ? s : "./" + s; | ||
| } | ||
| function hashString(v) { | ||
| return createHash("sha256").update(v).digest().toString("hex").slice(0, 12); | ||
| } | ||
| const VALID_ID_PREFIX = `/@id/`; | ||
| const NULL_BYTE_PLACEHOLDER = `__x00__`; | ||
| const FS_PREFIX = `/@fs/`; | ||
| function wrapId(id) { | ||
| return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER); | ||
| } | ||
| function withTrailingSlash(path$1) { | ||
| if (path$1[path$1.length - 1] !== "/") return `${path$1}/`; | ||
| return path$1; | ||
| } | ||
| const postfixRE = /[?#].*$/; | ||
| function cleanUrl(url) { | ||
| return url.replace(postfixRE, ""); | ||
| } | ||
| function splitFileAndPostfix(path$1) { | ||
| const file = cleanUrl(path$1); | ||
| return { | ||
| file, | ||
| postfix: path$1.slice(file.length) | ||
| }; | ||
| } | ||
| const windowsSlashRE = /\\/g; | ||
| function slash(p) { | ||
| return p.replace(windowsSlashRE, "/"); | ||
| } | ||
| const isWindows = typeof process !== "undefined" && process.platform === "win32"; | ||
| function injectQuery(url, queryToInject) { | ||
| const { file, postfix } = splitFileAndPostfix(url); | ||
| return `${isWindows ? slash(file) : file}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : postfix}`; | ||
| } | ||
| function normalizeResolvedIdToUrl(environment, url, resolved) { | ||
| const root = environment.config.root; | ||
| const depsOptimizer = environment.depsOptimizer; | ||
| if (resolved.id.startsWith(withTrailingSlash(root))) url = resolved.id.slice(root.length); | ||
| else if (depsOptimizer?.isOptimizedDepFile(resolved.id) || resolved.id !== "/@react-refresh" && path.isAbsolute(resolved.id) && fs.existsSync(cleanUrl(resolved.id))) url = path.posix.join(FS_PREFIX, resolved.id); | ||
| else url = resolved.id; | ||
| if (url[0] !== "." && url[0] !== "/") url = wrapId(resolved.id); | ||
| return url; | ||
| } | ||
| function normalizeViteImportAnalysisUrl(environment, id) { | ||
| let url = normalizeResolvedIdToUrl(environment, id, { id }); | ||
| if (environment.config.consumer === "client") { | ||
| const mod = environment.moduleGraph.getModuleById(id); | ||
| if (mod && mod.lastHMRTimestamp > 0) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`); | ||
| } | ||
| return url; | ||
| } | ||
| function evalValue(rawValue) { | ||
| return new Function(` | ||
| var console, exports, global, module, process, require | ||
| return (\n${rawValue}\n) | ||
| `)(); | ||
| } | ||
| const directRequestRE = /(\?|&)direct=?(?:&|$)/; | ||
| function assetsPlugin(pluginOpts) { | ||
| let server; | ||
| let resolvedConfig; | ||
| const importAssetsMetaMap = {}; | ||
| const bundleMap = {}; | ||
| async function processAssetsImport(ctx, id, options) { | ||
| if (ctx.environment.mode === "dev") { | ||
| const result = { | ||
| entry: void 0, | ||
| js: [], | ||
| css: [] | ||
| }; | ||
| const environment = server.environments[options.environment]; | ||
| assert$1(environment, `Unknown environment: ${options.environment}`); | ||
| if (options.environment === "client") result.entry = normalizeViteImportAnalysisUrl(environment, id); | ||
| if (environment.name !== "client") { | ||
| const collected = await collectCss(environment, id, { eager: pluginOpts?.experimental?.devEagerTransform ?? true }); | ||
| result.css = collected.hrefs.map((href, i) => ({ | ||
| href, | ||
| "data-vite-dev-id": collected.ids[i] | ||
| })); | ||
| } | ||
| return JSON.stringify(result); | ||
| } else { | ||
| const map = importAssetsMetaMap[options.environment] ??= {}; | ||
| const meta = { | ||
| id, | ||
| key: path.relative(resolvedConfig.root, id), | ||
| importerEnvironment: ctx.environment.name, | ||
| isEntry: !!(map[id]?.isEntry || options.isEntry) | ||
| }; | ||
| map[id] = meta; | ||
| return `__assets_manifest[${JSON.stringify(options.environment)}][${JSON.stringify(meta.key)}]`; | ||
| } | ||
| } | ||
| let writeAssetsManifestCalled = false; | ||
| async function writeAssetsManifest(builder) { | ||
| if (writeAssetsManifestCalled) return; | ||
| writeAssetsManifestCalled = true; | ||
| const manifest = {}; | ||
| for (const [environmentName, metas] of Object.entries(importAssetsMetaMap)) { | ||
| const bundle = bundleMap[environmentName]; | ||
| const assetDepsMap = collectAssetDeps(bundle); | ||
| for (const [id, meta] of Object.entries(metas)) { | ||
| const found = assetDepsMap[id]; | ||
| if (!found) { | ||
| builder.config.logger.error(`[vite-plugin-fullstack] failed to find built chunk for ${meta.id} imported by ${meta.importerEnvironment} environment`); | ||
| return; | ||
| } | ||
| const result = { | ||
| js: [], | ||
| css: [] | ||
| }; | ||
| const { chunk, deps } = found; | ||
| if (environmentName === "client") { | ||
| result.entry = `/${chunk.fileName}`; | ||
| result.js = deps.js.map((fileName) => ({ href: `/${fileName}` })); | ||
| } | ||
| result.css = deps.css.map((fileName) => ({ href: `/${fileName}` })); | ||
| if (!builder.environments[environmentName].config.build.cssCodeSplit) { | ||
| const singleCss = Object.values(bundle).find((v) => v.type === "asset" && v.originalFileNames.includes("style.css")); | ||
| if (singleCss) result.css.push({ href: `/${singleCss.fileName}` }); | ||
| } | ||
| (manifest[environmentName] ??= {})[meta.key] = result; | ||
| } | ||
| } | ||
| const importerEnvironments = new Set(Object.values(importAssetsMetaMap).flatMap((metas) => Object.values(metas)).flatMap((meta) => meta.importerEnvironment)); | ||
| for (const environmentName of importerEnvironments) { | ||
| const outDir = builder.environments[environmentName].config.build.outDir; | ||
| fs.writeFileSync(path.join(outDir, BUILD_ASSETS_MANIFEST_NAME), `export default ${JSON.stringify(manifest, null, 2)};`); | ||
| const clientOutDir = builder.environments["client"].config.build.outDir; | ||
| for (const asset of Object.values(bundleMap[environmentName])) if (asset.type === "asset") { | ||
| const srcFile = path.join(outDir, asset.fileName); | ||
| const destFile = path.join(clientOutDir, asset.fileName); | ||
| fs.mkdirSync(path.dirname(destFile), { recursive: true }); | ||
| fs.copyFileSync(srcFile, destFile); | ||
| } | ||
| } | ||
| } | ||
| return [ | ||
| { | ||
| name: "fullstack:assets", | ||
| sharedDuringBuild: true, | ||
| configureServer(server_) { | ||
| server = server_; | ||
| }, | ||
| configResolved(config) { | ||
| resolvedConfig = config; | ||
| }, | ||
| configEnvironment(name) { | ||
| if ((pluginOpts?.serverEnvironments ?? ["ssr"]).includes(name)) return { build: { emitAssets: true } }; | ||
| }, | ||
| transform: { async handler(code, id, _options) { | ||
| if (!code.includes("import.meta.vite.assets")) return; | ||
| const output = new MagicString(code); | ||
| const strippedCode = stripLiteral(code); | ||
| const newImports = /* @__PURE__ */ new Set(); | ||
| for (const match of code.matchAll(/import\.meta\.vite\.assets\(([\s\S]*?)\)/dg)) { | ||
| const [start, end] = match.indices[0]; | ||
| if (!strippedCode.slice(start, end).includes("import.meta.vite.assets")) continue; | ||
| if (this.environment.name === "client") { | ||
| const replacement$1 = `(${JSON.stringify(EMPTY_ASSETS)})`; | ||
| output.update(start, end, replacement$1); | ||
| continue; | ||
| } | ||
| const argCode = match[1].trim(); | ||
| const options = { | ||
| import: id, | ||
| environment: void 0, | ||
| asEntry: false | ||
| }; | ||
| if (argCode) { | ||
| const argValue = evalValue(argCode); | ||
| Object.assign(options, argValue); | ||
| } | ||
| const environments = options.environment ? [options.environment] : ["client", this.environment.name]; | ||
| const importedNames = []; | ||
| for (const environment of environments) { | ||
| const importSource = toAssetsVirtual({ | ||
| import: options.import, | ||
| importer: id, | ||
| environment, | ||
| entry: options.asEntry ? "1" : "" | ||
| }); | ||
| const importedName = `__assets_${hashString(importSource)}`; | ||
| newImports.add(`;import ${importedName} from ${JSON.stringify(importSource)};\n`); | ||
| importedNames.push(importedName); | ||
| } | ||
| let replacement = importedNames[0]; | ||
| if (importedNames.length > 1) { | ||
| newImports.add(`;import * as __assets_runtime from "virtual:fullstack/runtime";\n`); | ||
| replacement = `__assets_runtime.mergeAssets(${importedNames.join(", ")})`; | ||
| } | ||
| output.update(start, end, `(${replacement})`); | ||
| } | ||
| if (output.hasChanged()) { | ||
| for (const newImport of newImports) output.append(newImport); | ||
| return { | ||
| code: output.toString(), | ||
| map: output.generateMap({ hires: "boundary" }) | ||
| }; | ||
| } | ||
| } }, | ||
| resolveId: { handler(source) { | ||
| if (source.startsWith("virtual:fullstack/assets?")) return "\0" + source; | ||
| if (source === "virtual:fullstack/assets-manifest") { | ||
| assert$1.notEqual(this.environment.name, "client"); | ||
| assert$1.equal(this.environment.mode, "build"); | ||
| return { | ||
| id: source, | ||
| external: true | ||
| }; | ||
| } | ||
| if (source === "virtual:fullstack/runtime") return { id: source }; | ||
| } }, | ||
| load: { async handler(id) { | ||
| if (id === "virtual:fullstack/runtime") return runtimeUtils(); | ||
| const parsed = parseAssetsVirtual(id); | ||
| if (!parsed) return; | ||
| assert$1.notEqual(this.environment.name, "client"); | ||
| const resolved = await this.resolve(parsed.import, parsed.importer); | ||
| assert$1(resolved, `Failed to resolve: ${parsed.import}`); | ||
| const s = new MagicString(""); | ||
| const code = await processAssetsImport(this, resolved.id, { | ||
| environment: parsed.environment, | ||
| isEntry: !!parsed.entry | ||
| }); | ||
| s.append(`export default ${code};\n`); | ||
| if (this.environment.mode === "build") s.prepend(`import __assets_manifest from "virtual:fullstack/assets-manifest";\n`); | ||
| return s.toString(); | ||
| } }, | ||
| renderChunk(code, chunk) { | ||
| if (code.includes("virtual:fullstack/assets-manifest")) { | ||
| const replacement = normalizeRelativePath(path.relative(path.join(chunk.fileName, ".."), BUILD_ASSETS_MANIFEST_NAME)); | ||
| code = code.replaceAll("virtual:fullstack/assets-manifest", () => replacement); | ||
| return { code }; | ||
| } | ||
| }, | ||
| writeBundle(_options, bundle) { | ||
| bundleMap[this.environment.name] = bundle; | ||
| }, | ||
| buildStart() { | ||
| if (this.environment.mode == "build" && this.environment.name === "client") { | ||
| if (importAssetsMetaMap["client"]) { | ||
| for (const meta of Object.values(importAssetsMetaMap["client"])) if (meta.isEntry) this.emitFile({ | ||
| type: "chunk", | ||
| id: meta.id, | ||
| preserveSignature: "exports-only" | ||
| }); | ||
| } | ||
| } | ||
| }, | ||
| buildApp: { | ||
| order: "pre", | ||
| async handler(builder) { | ||
| builder.writeAssetsManifest = async () => { | ||
| await writeAssetsManifest(builder); | ||
| }; | ||
| } | ||
| } | ||
| }, | ||
| { | ||
| name: "fullstack:write-assets-manifest-post", | ||
| buildApp: { | ||
| order: "post", | ||
| async handler(builder) { | ||
| await builder.writeAssetsManifest(); | ||
| } | ||
| } | ||
| }, | ||
| { | ||
| name: "fullstack:assets-query", | ||
| sharedDuringBuild: true, | ||
| resolveId: { | ||
| order: "pre", | ||
| handler(source) { | ||
| const { query } = parseIdQuery(source); | ||
| if (typeof query["assets"] !== "undefined") { | ||
| if (this.environment.name === "client") return `\0virtual:fullstack/empty-assets`; | ||
| } | ||
| if (source === "virtual:fullstack/runtime") return source; | ||
| } | ||
| }, | ||
| load: { async handler(id) { | ||
| if (id === "\0virtual:fullstack/empty-assets") return `export default ${JSON.stringify(EMPTY_ASSETS)}`; | ||
| if (id === "virtual:fullstack/runtime") return runtimeUtils(); | ||
| const { filename, query } = parseIdQuery(id); | ||
| const value = query["assets"]; | ||
| if (typeof value !== "undefined") { | ||
| const s = new MagicString(""); | ||
| const codes = []; | ||
| if (value) { | ||
| const code = await processAssetsImport(this, filename, { | ||
| environment: value, | ||
| isEntry: value === "client" | ||
| }); | ||
| codes.push(code); | ||
| } else { | ||
| const code1 = await processAssetsImport(this, filename, { | ||
| environment: "client", | ||
| isEntry: false | ||
| }); | ||
| const code2 = await processAssetsImport(this, filename, { | ||
| environment: this.environment.name, | ||
| isEntry: false | ||
| }); | ||
| codes.push(code1, code2); | ||
| } | ||
| s.append(` | ||
| import * as __assets_runtime from "virtual:fullstack/runtime";\n | ||
| export default __assets_runtime.mergeAssets(${codes.join(", ")}); | ||
| `); | ||
| if (this.environment.mode === "build") s.prepend(`import __assets_manifest from "virtual:fullstack/assets-manifest";\n`); | ||
| return { | ||
| code: s.toString(), | ||
| moduleSideEffects: false | ||
| }; | ||
| } | ||
| } }, | ||
| hotUpdate(ctx) { | ||
| if (this.environment.name === "rsc") { | ||
| const mods = collectModuleDependents(ctx.modules); | ||
| for (const mod of mods) if (mod.id) { | ||
| const ids = [ | ||
| `${mod.id}?assets`, | ||
| `${mod.id}?assets=client`, | ||
| `${mod.id}?assets=${this.environment.name}` | ||
| ]; | ||
| for (const id of ids) invalidteModuleById(this.environment, id); | ||
| } | ||
| } | ||
| } | ||
| }, | ||
| { | ||
| ...createVirtualPlugin("fullstack/client-fallback", () => "export {}"), | ||
| configEnvironment: { | ||
| order: "post", | ||
| handler(name, config, _env) { | ||
| if (name === "client") { | ||
| if ((pluginOpts?.experimental?.clientBuildFallback ?? true) && !config.build?.rollupOptions?.input) return { build: { rollupOptions: { input: { __fallback: "virtual:fullstack/client-fallback" } } } }; | ||
| } | ||
| } | ||
| }, | ||
| generateBundle(_optoins, bundle) { | ||
| if (this.environment.name !== "client") return; | ||
| for (const [k, v] of Object.entries(bundle)) if (v.type === "chunk" && v.name === "__fallback") delete bundle[k]; | ||
| } | ||
| }, | ||
| patchViteClientPlugin(), | ||
| patchVueScopeCssHmr(), | ||
| patchCssLinkSelfAccept() | ||
| ]; | ||
| } | ||
| const EMPTY_ASSETS = { | ||
| js: [], | ||
| css: [] | ||
| }; | ||
| const BUILD_ASSETS_MANIFEST_NAME = "__fullstack_assets_manifest.js"; | ||
| async function collectCss(environment, entryId, options) { | ||
| const visited = /* @__PURE__ */ new Set(); | ||
| const cssIds = /* @__PURE__ */ new Set(); | ||
| async function recurse(id) { | ||
| if (visited.has(id) || parseAssetsVirtual(id) || "assets" in parseIdQuery(id).query) return; | ||
| visited.add(id); | ||
| const mod = environment.moduleGraph.getModuleById(id); | ||
| if (!mod) return; | ||
| if (options.eager && !mod?.transformResult) try { | ||
| await environment.transformRequest(id); | ||
| } catch (e) { | ||
| console.error(`[collectCss] Failed to transform '${id}'`, e); | ||
| } | ||
| for (const next of mod?.importedModules ?? []) if (next.id) if (isCSSRequest(next.id)) { | ||
| if (hasSpecialCssQuery(next.id)) continue; | ||
| cssIds.add(next.id); | ||
| } else await recurse(next.id); | ||
| } | ||
| await recurse(entryId); | ||
| const hrefs = [...cssIds].map((id) => normalizeViteImportAnalysisUrl(environment, id)); | ||
| return { | ||
| ids: [...cssIds], | ||
| hrefs | ||
| }; | ||
| } | ||
| function invalidteModuleById(environment, id) { | ||
| const mod = environment.moduleGraph.getModuleById(id); | ||
| if (mod) environment.moduleGraph.invalidateModule(mod); | ||
| return mod; | ||
| } | ||
| function collectModuleDependents(mods) { | ||
| const visited = /* @__PURE__ */ new Set(); | ||
| function recurse(mod) { | ||
| if (visited.has(mod)) return; | ||
| visited.add(mod); | ||
| for (const importer of mod.importers) recurse(importer); | ||
| } | ||
| for (const mod of mods) recurse(mod); | ||
| return [...visited]; | ||
| } | ||
| function hasSpecialCssQuery(id) { | ||
| return /[?&](url|inline|raw)(\b|=|&|$)/.test(id); | ||
| } | ||
| function collectAssetDeps(bundle) { | ||
| const chunkToDeps = /* @__PURE__ */ new Map(); | ||
| for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") chunkToDeps.set(chunk, collectAssetDepsInner(chunk.fileName, bundle)); | ||
| const idToDeps = {}; | ||
| for (const [chunk, deps] of chunkToDeps.entries()) for (const id of chunk.moduleIds) idToDeps[id] = { | ||
| chunk, | ||
| deps | ||
| }; | ||
| return idToDeps; | ||
| } | ||
| function collectAssetDepsInner(fileName, bundle) { | ||
| const visited = /* @__PURE__ */ new Set(); | ||
| const css = []; | ||
| function recurse(k) { | ||
| if (visited.has(k)) return; | ||
| visited.add(k); | ||
| const v = bundle[k]; | ||
| assert$1(v, `Not found '${k}' in the bundle`); | ||
| if (v.type === "chunk") { | ||
| css.push(...v.viteMetadata?.importedCss ?? []); | ||
| for (const k2 of v.imports) if (k2 in bundle) recurse(k2); | ||
| } | ||
| } | ||
| recurse(fileName); | ||
| return { | ||
| js: [...visited], | ||
| css: [...new Set(css)] | ||
| }; | ||
| } | ||
| function patchViteClientPlugin() { | ||
| const viteClientPath = normalizePath(fileURLToPath(import.meta.resolve("vite/dist/client/client.mjs"))); | ||
| function endIndexOf(code, searchValue) { | ||
| const i = code.lastIndexOf(searchValue); | ||
| return i === -1 ? i : i + searchValue.length; | ||
| } | ||
| return { | ||
| name: "fullstack:patch-vite-client", | ||
| transform: { handler(code, id) { | ||
| if (id === viteClientPath) { | ||
| if (code.includes("linkSheetsMap")) return; | ||
| const s = new MagicString(code); | ||
| s.prependLeft(code.indexOf("const sheetsMap"), `\ | ||
| const linkSheetsMap = new Map(); | ||
| document | ||
| .querySelectorAll('link[rel="stylesheet"][data-vite-dev-id]') | ||
| .forEach((el) => { | ||
| linkSheetsMap.set(el.getAttribute('data-vite-dev-id'), el) | ||
| }); | ||
| `); | ||
| s.appendLeft(endIndexOf(code, `function updateStyle(id, content) {`), `if (linkSheetsMap.has(id)) { return }`); | ||
| s.appendLeft(endIndexOf(code, `function removeStyle(id) {`), ` | ||
| const link = linkSheetsMap.get(id); | ||
| if (link) { | ||
| document | ||
| .querySelectorAll( | ||
| 'link[rel="stylesheet"][data-vite-dev-id]', | ||
| ) | ||
| .forEach((el) => { | ||
| if (el.getAttribute('data-vite-dev-id') === id) { | ||
| el.remove() | ||
| } | ||
| }) | ||
| linkSheetsMap.delete(id) | ||
| } | ||
| `); | ||
| return s.toString(); | ||
| } | ||
| } } | ||
| }; | ||
| } | ||
| function patchVueScopeCssHmr() { | ||
| return { | ||
| name: "fullstack:patch-vue-scoped-css-hmr", | ||
| configureServer(server) { | ||
| server.middlewares.use((req, _res, next) => { | ||
| if (req.headers.accept?.includes("text/css") && req.url?.includes("&lang.css=")) req.url = req.url.replace("&lang.css=", "?lang.css"); | ||
| next(); | ||
| }); | ||
| } | ||
| }; | ||
| } | ||
| function patchCssLinkSelfAccept() { | ||
| return { | ||
| name: "fullstack:patch-css-link-self-accept", | ||
| apply: "serve", | ||
| transform: { | ||
| order: "post", | ||
| handler(_code, id, _options) { | ||
| if (this.environment.name === "client" && this.environment.mode === "dev" && isCSSRequest(id) && directRequestRE.test(id)) { | ||
| const mod = this.environment.moduleGraph.getModuleById(id); | ||
| if (mod && !mod.isSelfAccepting) mod.isSelfAccepting = true; | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| function runtimeUtils() { | ||
| return ` | ||
| export function mergeAssets(...args) { | ||
| const js = uniqBy(args.flatMap((h) => h.js), (a) => a.href); | ||
| const css = uniqBy(args.flatMap((h) => h.css), (a) => a.href); | ||
| const entry = args.filter((arg) => arg.entry)?.[0]?.entry; | ||
| const raw = { entry, js, css }; | ||
| return { ...raw, merge: (...args$1) => mergeAssets(raw, ...args$1) }; | ||
| } | ||
| function uniqBy(array, key) { | ||
| const seen = new Set(); | ||
| return array.filter((item) => { | ||
| const k = key(item); | ||
| if (seen.has(k)) return false; | ||
| seen.add(k); | ||
| return true; | ||
| }); | ||
| }`; | ||
| } | ||
| //#endregion | ||
| export { assetsPlugin as t }; |
| import "../../_libs/c12.mjs"; | ||
| import "../../_libs/gen-mapping.mjs"; | ||
| import "../../_libs/magic-string.mjs"; | ||
| import "../../_libs/acorn.mjs"; | ||
| import "../../_libs/confbox.mjs"; | ||
| import "../../_libs/local-pkg.mjs"; | ||
| import "../../_libs/js-tokens.mjs"; | ||
| import "../../_libs/strip-literal.mjs"; | ||
| import { n as detectImportsAcorn, r as traveseScopes, t as createVirtualImportsAcronWalker } from "../../_libs/unimport.mjs"; | ||
| import "../../_libs/estree-walker.mjs"; | ||
| export { createVirtualImportsAcronWalker, detectImportsAcorn, traveseScopes }; |
| import { c as findNearestFile, d as readGitConfig, f as readPackageJSON, l as findWorkspaceDir, m as resolvePackageJSON, p as resolveGitConfig, s as findFile, u as parseGitConfig } from "../../_libs/c12.mjs"; | ||
| export { findFile, findNearestFile, findWorkspaceDir, parseGitConfig, readGitConfig, readPackageJSON, resolveGitConfig, resolvePackageJSON }; |
| import { a as loadDotenv, i as loadConfig, o as setupDotenv, r as SUPPORTED_EXTENSIONS, t as watchConfig } from "../../_libs/c12.mjs"; | ||
| export { SUPPORTED_EXTENSIONS, loadConfig, loadDotenv, setupDotenv, watchConfig }; |
| import { n as createProxyServer, t as ProxyServer } from "../../_libs/httpxy.mjs"; | ||
| export { ProxyServer, createProxyServer }; |
| import "../../_libs/c12.mjs"; | ||
| import { a as addDependency, c as installDependencies, l as packageManagers, o as addDevDependency, s as detectPackageManager } from "../../_libs/giget.mjs"; | ||
| export { addDependency, addDevDependency, detectPackageManager, installDependencies, packageManagers }; |
| import "../../_libs/c12.mjs"; | ||
| import { n as registryProvider, t as downloadTemplate } from "../../_libs/giget.mjs"; | ||
| export { downloadTemplate, registryProvider }; |
| import { i as watch, n as WatchHelper, r as esm_default, t as FSWatcher } from "../../_libs/chokidar.mjs"; | ||
| export { FSWatcher, WatchHelper, esm_default as default, watch }; |
| import "../../_libs/c12.mjs"; | ||
| import { i as Cu } from "../../_libs/confbox.mjs"; | ||
| export { Cu as parseJSON5 }; |
| import { _ as h } from "../../_libs/c12.mjs"; | ||
| import "../../_libs/confbox.mjs"; | ||
| export { h as parseJSONC }; |
| import "../../_libs/giget.mjs"; | ||
| import { t as require_multipart_parser } from "../../_libs/node-fetch-native.mjs"; | ||
| export default require_multipart_parser(); | ||
| export { }; |
| import "../../_libs/c12.mjs"; | ||
| import { t as Q } from "../../_libs/confbox.mjs"; | ||
| export { Q as parseTOML }; |
| import "../../_libs/c12.mjs"; | ||
| import { n as gr, r as mr } from "../../_libs/confbox.mjs"; | ||
| export { mr as parseYAML, gr as stringifyYAML }; |
| 'use strict'; | ||
| let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true; | ||
| if (typeof process !== 'undefined') { | ||
| ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}); | ||
| isTTY = process.stdout && process.stdout.isTTY; | ||
| } | ||
| const $ = { | ||
| enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && ( | ||
| FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY | ||
| ), | ||
| // modifiers | ||
| reset: init(0, 0), | ||
| bold: init(1, 22), | ||
| dim: init(2, 22), | ||
| italic: init(3, 23), | ||
| underline: init(4, 24), | ||
| inverse: init(7, 27), | ||
| hidden: init(8, 28), | ||
| strikethrough: init(9, 29), | ||
| // colors | ||
| black: init(30, 39), | ||
| red: init(31, 39), | ||
| green: init(32, 39), | ||
| yellow: init(33, 39), | ||
| blue: init(34, 39), | ||
| magenta: init(35, 39), | ||
| cyan: init(36, 39), | ||
| white: init(37, 39), | ||
| gray: init(90, 39), | ||
| grey: init(90, 39), | ||
| // background colors | ||
| bgBlack: init(40, 49), | ||
| bgRed: init(41, 49), | ||
| bgGreen: init(42, 49), | ||
| bgYellow: init(43, 49), | ||
| bgBlue: init(44, 49), | ||
| bgMagenta: init(45, 49), | ||
| bgCyan: init(46, 49), | ||
| bgWhite: init(47, 49) | ||
| }; | ||
| function run(arr, str) { | ||
| let i=0, tmp, beg='', end=''; | ||
| for (; i < arr.length; i++) { | ||
| tmp = arr[i]; | ||
| beg += tmp.open; | ||
| end += tmp.close; | ||
| if (!!~str.indexOf(tmp.close)) { | ||
| str = str.replace(tmp.rgx, tmp.close + tmp.open); | ||
| } | ||
| } | ||
| return beg + str + end; | ||
| } | ||
| function chain(has, keys) { | ||
| let ctx = { has, keys }; | ||
| ctx.reset = $.reset.bind(ctx); | ||
| ctx.bold = $.bold.bind(ctx); | ||
| ctx.dim = $.dim.bind(ctx); | ||
| ctx.italic = $.italic.bind(ctx); | ||
| ctx.underline = $.underline.bind(ctx); | ||
| ctx.inverse = $.inverse.bind(ctx); | ||
| ctx.hidden = $.hidden.bind(ctx); | ||
| ctx.strikethrough = $.strikethrough.bind(ctx); | ||
| ctx.black = $.black.bind(ctx); | ||
| ctx.red = $.red.bind(ctx); | ||
| ctx.green = $.green.bind(ctx); | ||
| ctx.yellow = $.yellow.bind(ctx); | ||
| ctx.blue = $.blue.bind(ctx); | ||
| ctx.magenta = $.magenta.bind(ctx); | ||
| ctx.cyan = $.cyan.bind(ctx); | ||
| ctx.white = $.white.bind(ctx); | ||
| ctx.gray = $.gray.bind(ctx); | ||
| ctx.grey = $.grey.bind(ctx); | ||
| ctx.bgBlack = $.bgBlack.bind(ctx); | ||
| ctx.bgRed = $.bgRed.bind(ctx); | ||
| ctx.bgGreen = $.bgGreen.bind(ctx); | ||
| ctx.bgYellow = $.bgYellow.bind(ctx); | ||
| ctx.bgBlue = $.bgBlue.bind(ctx); | ||
| ctx.bgMagenta = $.bgMagenta.bind(ctx); | ||
| ctx.bgCyan = $.bgCyan.bind(ctx); | ||
| ctx.bgWhite = $.bgWhite.bind(ctx); | ||
| return ctx; | ||
| } | ||
| function init(open, close) { | ||
| let blk = { | ||
| open: `\x1b[${open}m`, | ||
| close: `\x1b[${close}m`, | ||
| rgx: new RegExp(`\\x1b\\[${close}m`, 'g') | ||
| }; | ||
| return function (txt) { | ||
| if (this !== void 0 && this.has !== void 0) { | ||
| !!~this.has.indexOf(open) || (this.has.push(open),this.keys.push(blk)); | ||
| return txt === void 0 ? this : $.enabled ? run(this.keys, txt+'') : txt+''; | ||
| } | ||
| return txt === void 0 ? chain([open], [blk]) : $.enabled ? run([blk], txt+'') : txt+''; | ||
| }; | ||
| } | ||
| module.exports = $; |
| import { | ||
| colors, | ||
| stripAnsi | ||
| } from "./chunk-4L7RY2JA.js"; | ||
| import { | ||
| publicDirURL | ||
| } from "./chunk-OSUFJZHZ.js"; | ||
| import { | ||
| BaseComponent | ||
| } from "./chunk-4YEN7HVQ.js"; | ||
| // src/templates/error_stack_source/main.ts | ||
| import { extname } from "path"; | ||
| import { highlightText } from "@speed-highlight/core"; | ||
| import { highlightText as cliHighlightText } from "@speed-highlight/core/terminal"; | ||
| var GUTTER = "\u2503"; | ||
| var POINTER = "\u276F"; | ||
| var LANGS_MAP = { | ||
| ".tsx": "ts", | ||
| ".jsx": "js", | ||
| ".js": "js", | ||
| ".ts": "ts", | ||
| ".css": "css", | ||
| ".json": "json", | ||
| ".html": "html", | ||
| ".astro": "ts", | ||
| ".vue": "ts" | ||
| }; | ||
| var ErrorStackSource = class extends BaseComponent { | ||
| cssFile = new URL("./error_stack_source/style.css", publicDirURL); | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML(props) { | ||
| const frame = props.frame; | ||
| if (frame.type === "native" || !frame.source || !frame.fileName) { | ||
| return ""; | ||
| } | ||
| const language = LANGS_MAP[extname(frame.fileName)] ?? "plain"; | ||
| const highlightMarginTop = `${frame.source.findIndex((chunk) => { | ||
| return chunk.lineNumber === frame.lineNumber; | ||
| }) * 24}px`; | ||
| const highlight = `<div class="line-highlight" style="margin-top: ${highlightMarginTop}"></div>`; | ||
| let code = await highlightText( | ||
| frame.source.map((chunk) => chunk.chunk).join("\n"), | ||
| language, | ||
| true | ||
| ); | ||
| code = code.replace( | ||
| '<div class="shj-numbers">', | ||
| `<div class="shj-numbers" style="counter-set: line ${frame.source[0].lineNumber - 1}">` | ||
| ); | ||
| return `<pre><code class="shj-lang-js">${highlight}${code}</code></pre>`; | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI(props) { | ||
| const frame = props.frame; | ||
| if (frame.type === "native" || !frame.source || !frame.fileName) { | ||
| return ""; | ||
| } | ||
| const language = LANGS_MAP[extname(frame.fileName)] ?? "plain"; | ||
| const largestLineNumber = Math.max(...frame.source.map(({ lineNumber }) => lineNumber)); | ||
| const lineNumberCols = String(largestLineNumber).length; | ||
| const code = frame.source.map(({ chunk }) => chunk).join("\n"); | ||
| const highlighted = await cliHighlightText(code, language); | ||
| return ` | ||
| ${highlighted.split("\n").map((line, index) => { | ||
| const lineNumber = frame.source[index].lineNumber; | ||
| const alignedLineNumber = String(lineNumber).padStart(lineNumberCols, " "); | ||
| if (lineNumber === props.frame.lineNumber) { | ||
| return ` ${colors.bgRed(`${POINTER} ${alignedLineNumber} ${GUTTER} ${stripAnsi(line)}`)}`; | ||
| } | ||
| return ` ${colors.dim(alignedLineNumber)} ${colors.dim(GUTTER)} ${line}`; | ||
| }).join("\n")} | ||
| `; | ||
| } | ||
| }; | ||
| export { | ||
| ErrorStackSource | ||
| }; |
| // src/component.ts | ||
| import { readFile } from "fs/promises"; | ||
| var BaseComponent = class { | ||
| #cachedStyles; | ||
| #cachedScript; | ||
| /** | ||
| * A flag to know if we are in dev mode or not. In dev mode, | ||
| * the styles and scripts are refetched from the disk. | ||
| * Otherwise they are cached. | ||
| */ | ||
| #inDevMode; | ||
| /** | ||
| * Absolute path to the frontend JavaScript that should be | ||
| * injected within the HTML head. The JavaScript does not | ||
| * get transpiled, hence it should work cross browser by | ||
| * default. | ||
| */ | ||
| scriptFile; | ||
| /** | ||
| * Absolute path to the CSS file that should be injected | ||
| * within the HTML head. | ||
| */ | ||
| cssFile; | ||
| constructor(devMode) { | ||
| this.#inDevMode = devMode; | ||
| } | ||
| /** | ||
| * Returns the styles for the component. The null value | ||
| * is not returned if no styles are associated with | ||
| * the component | ||
| */ | ||
| async getStyles() { | ||
| if (!this.cssFile) { | ||
| return null; | ||
| } | ||
| if (this.#inDevMode) { | ||
| return await readFile(this.cssFile, "utf-8"); | ||
| } | ||
| this.#cachedStyles = this.#cachedStyles ?? await readFile(this.cssFile, "utf-8"); | ||
| return this.#cachedStyles; | ||
| } | ||
| /** | ||
| * Returns the frontend script for the component. The null | ||
| * value is not returned if no styles are associated | ||
| * with the component | ||
| */ | ||
| async getScript() { | ||
| if (!this.scriptFile) { | ||
| return null; | ||
| } | ||
| if (this.#inDevMode) { | ||
| return await readFile(this.scriptFile, "utf-8"); | ||
| } | ||
| this.#cachedScript = this.#cachedScript ?? await readFile(this.scriptFile, "utf-8"); | ||
| return this.#cachedScript; | ||
| } | ||
| }; | ||
| export { | ||
| BaseComponent | ||
| }; |
| import { | ||
| colors, | ||
| wordWrap | ||
| } from "./chunk-4L7RY2JA.js"; | ||
| import { | ||
| publicDirURL | ||
| } from "./chunk-OSUFJZHZ.js"; | ||
| import { | ||
| BaseComponent | ||
| } from "./chunk-4YEN7HVQ.js"; | ||
| // src/templates/error_info/main.ts | ||
| var ERROR_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="24" height="24" fill="none"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 7v6m0 4.01.01-.011M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10Z"/></svg>`; | ||
| var HINT_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="24" height="24" fill="none"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="m21 2-1 1M3 2l1 1m17 13-1-1M3 16l1-1m5 3h6m-5 3h4M12 3C8 3 5.952 4.95 6 8c.023 1.487.5 2.5 1.5 3.5S9 13 9 15h6c0-2 .5-2.5 1.5-3.5h0c1-1 1.477-2.013 1.5-3.5.048-3.05-2-5-6-5Z"/></svg>`; | ||
| var COPY_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z" /><path d="M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1" /></svg>`; | ||
| function htmlAttributeEscape(value) { | ||
| return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">"); | ||
| } | ||
| var ErrorInfo = class extends BaseComponent { | ||
| cssFile = new URL("./error_info/style.css", publicDirURL); | ||
| scriptFile = new URL("./error_info/script.js", publicDirURL); | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML(props) { | ||
| return `<section> | ||
| <h4 id="error-name">${props.error.name}</h4> | ||
| <h1 id="error-title">${props.title}</h1> | ||
| </section> | ||
| <section> | ||
| <div class="card"> | ||
| <div class="card-body"> | ||
| <h2 id="error-message"> | ||
| <span>${ERROR_ICON_SVG}</span> | ||
| <span>${props.error.message}</span> | ||
| <button | ||
| id="copy-error-btn" | ||
| data-error-text="${htmlAttributeEscape(`${props.error.name}: ${props.error.message}`)}" | ||
| onclick="copyErrorMessage(this)" | ||
| title="Copy error message" | ||
| aria-label="Copy error message to clipboard" | ||
| > | ||
| ${COPY_ICON_SVG} | ||
| </button> | ||
| </h2> | ||
| ${props.error.hint ? `<div id="error-hint"> | ||
| <span>${HINT_ICON_SVG}</span> | ||
| <span>${props.error.hint}</span> | ||
| </div>` : ""} | ||
| </div> | ||
| </div> | ||
| </section>`; | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI(props) { | ||
| const errorMessage = colors.red( | ||
| `\u2139 ${wordWrap(`${props.error.name}: ${props.error.message}`, { | ||
| width: process.stdout.columns, | ||
| indent: " ", | ||
| newLine: "\n", | ||
| escape: (value) => value | ||
| })}` | ||
| ); | ||
| const hint = props.error.hint ? ` | ||
| ${colors.blue("\u25C9")} ${colors.dim().italic( | ||
| wordWrap(props.error.hint.replace(/(<([^>]+)>)/gi, ""), { | ||
| width: process.stdout.columns, | ||
| indent: " ", | ||
| newLine: "\n", | ||
| escape: (value) => value | ||
| }) | ||
| )}` : ""; | ||
| return `${errorMessage}${hint}`; | ||
| } | ||
| }; | ||
| export { | ||
| ErrorInfo | ||
| }; |
| import { | ||
| publicDirURL | ||
| } from "./chunk-OSUFJZHZ.js"; | ||
| import { | ||
| BaseComponent | ||
| } from "./chunk-4YEN7HVQ.js"; | ||
| // src/templates/layout/main.ts | ||
| var Layout = class extends BaseComponent { | ||
| cssFile = new URL("./layout/style.css", publicDirURL); | ||
| scriptFile = new URL("./layout/script.js", publicDirURL); | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML(props) { | ||
| return `<!DOCTYPE html> | ||
| <html lang="en"> | ||
| <head> | ||
| <meta charset="UTF-8" /> | ||
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | ||
| <title>${props.title}</title> | ||
| <!-- STYLES --> | ||
| <!-- GLOBAL SCRIPT --> | ||
| </head> | ||
| <body> | ||
| <div id="layout"> | ||
| ${await props.children()} | ||
| </div> | ||
| <!-- SCRIPTS --> | ||
| </body> | ||
| </html>`; | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI(props) { | ||
| return ` | ||
| ${await props.children()} | ||
| `; | ||
| } | ||
| }; | ||
| export { | ||
| Layout | ||
| }; |
| import { | ||
| BaseComponent | ||
| } from "./chunk-4YEN7HVQ.js"; | ||
| // src/templates/error_metadata/main.ts | ||
| import { dump, themes } from "@poppinss/dumper/html"; | ||
| var ErrorMetadata = class extends BaseComponent { | ||
| #primitives = ["string", "boolean", "number", "undefined"]; | ||
| /** | ||
| * Formats the error row value | ||
| */ | ||
| #formatRowValue(value, dumpValue, cspNonce) { | ||
| if (dumpValue === true) { | ||
| return dump(value, { styles: themes.cssVariables, cspNonce }); | ||
| } | ||
| if (this.#primitives.includes(typeof value) || value === null) { | ||
| return value; | ||
| } | ||
| return dump(value, { styles: themes.cssVariables, cspNonce }); | ||
| } | ||
| /** | ||
| * Returns HTML fragment with HTML table containing rows | ||
| * metadata section rows | ||
| */ | ||
| #renderRows(rows, cspNonce) { | ||
| return `<table class="card-table"> | ||
| <tbody> | ||
| ${rows.map((row) => { | ||
| return `<tr> | ||
| <td class="table-key">${row.key}</td> | ||
| <td class="table-value"> | ||
| ${this.#formatRowValue(row.value, row.dump, cspNonce)} | ||
| </td> | ||
| </tr>`; | ||
| }).join("\n")} | ||
| </tbody> | ||
| </table>`; | ||
| } | ||
| /** | ||
| * Renders each section with its rows inside a table | ||
| */ | ||
| #renderSection(section, rows, cspNonce) { | ||
| return `<div> | ||
| <h4 class="card-subtitle">${section}</h4> | ||
| ${Array.isArray(rows) ? this.#renderRows(rows, cspNonce) : `<span>${this.#formatRowValue(rows.value, rows.dump, cspNonce)}</span>`} | ||
| </div>`; | ||
| } | ||
| /** | ||
| * Renders each group as a card | ||
| */ | ||
| #renderGroup(group, sections, cspNonce) { | ||
| return `<section> | ||
| <div class="card"> | ||
| <div class="card-heading"> | ||
| <h3 class="card-title">${group}</h3> | ||
| </div> | ||
| <div class="card-body"> | ||
| ${Object.keys(sections).map((section) => this.#renderSection(section, sections[section], cspNonce)).join("\n")} | ||
| </div> | ||
| </div> | ||
| </section>`; | ||
| } | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML(props) { | ||
| const groups = props.metadata.toJSON(); | ||
| const groupsNames = Object.keys(groups); | ||
| if (!groupsNames.length) { | ||
| return ""; | ||
| } | ||
| return groupsNames.map((group) => this.#renderGroup(group, groups[group], props.cspNonce)).join("\n"); | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI() { | ||
| return ""; | ||
| } | ||
| }; | ||
| export { | ||
| ErrorMetadata | ||
| }; |
| // src/public_dir.ts | ||
| var publicDirURL = new URL("./public/", import.meta.url); | ||
| export { | ||
| publicDirURL | ||
| }; |
| import { | ||
| colors | ||
| } from "./chunk-4L7RY2JA.js"; | ||
| import { | ||
| publicDirURL | ||
| } from "./chunk-OSUFJZHZ.js"; | ||
| import { | ||
| BaseComponent | ||
| } from "./chunk-4YEN7HVQ.js"; | ||
| // src/templates/error_cause/main.ts | ||
| import { dump, themes } from "@poppinss/dumper/html"; | ||
| import { dump as dumpCli } from "@poppinss/dumper/console"; | ||
| var ErrorCause = class extends BaseComponent { | ||
| cssFile = new URL("./error_cause/style.css", publicDirURL); | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML(props) { | ||
| if (!props.error.cause) { | ||
| return ""; | ||
| } | ||
| return `<section> | ||
| <div class="card"> | ||
| <div class="card-heading"> | ||
| <div> | ||
| <h3 class="card-title"> | ||
| Error Cause | ||
| </h3> | ||
| </div> | ||
| </div> | ||
| <div class="card-body"> | ||
| <div id="error-cause"> | ||
| ${dump(props.error.cause, { | ||
| cspNonce: props.cspNonce, | ||
| styles: themes.cssVariables, | ||
| inspectObjectPrototype: false, | ||
| inspectStaticMembers: false, | ||
| inspectArrayPrototype: false | ||
| })} | ||
| </div> | ||
| </div> | ||
| </div> | ||
| </section>`; | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI(props) { | ||
| if (!props.error.cause) { | ||
| return ""; | ||
| } | ||
| let depth = process.env.YOUCH_CAUSE ? Number(process.env.YOUCH_CAUSE) : 2; | ||
| if (Number.isNaN(depth)) { | ||
| depth = 2; | ||
| } | ||
| return ` | ||
| ${colors.red("[CAUSE]")} | ||
| ${dumpCli(props.error.cause, { | ||
| depth, | ||
| inspectObjectPrototype: false, | ||
| inspectStaticMembers: false, | ||
| inspectArrayPrototype: false | ||
| })}`; | ||
| } | ||
| }; | ||
| export { | ||
| ErrorCause | ||
| }; |
| import { | ||
| publicDirURL | ||
| } from "./chunk-OSUFJZHZ.js"; | ||
| import { | ||
| BaseComponent | ||
| } from "./chunk-4YEN7HVQ.js"; | ||
| // src/templates/header/main.ts | ||
| var DARK_MODE_SVG = `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M0 0h24v24H0z" stroke="none"/><path d="M12 3h.393a7.5 7.5 0 0 0 7.92 12.446A9 9 0 1 1 12 2.992z"/></svg>`; | ||
| var LIGHT_MODE_SVG = `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M0 0h24v24H0z" stroke="none"/><circle cx="12" cy="12" r="4"/><path d="M3 12h1m8-9v1m8 8h1m-9 8v1M5.6 5.6l.7.7m12.1-.7-.7.7m0 11.4.7.7m-12.1-.7-.7.7"/></svg>`; | ||
| var Header = class extends BaseComponent { | ||
| cssFile = new URL("./header/style.css", publicDirURL); | ||
| scriptFile = new URL("./header/script.js", publicDirURL); | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML() { | ||
| return `<header id="header"> | ||
| <div id="header-actions"> | ||
| <div id="toggle-theme-container"> | ||
| <input type="checkbox" id="toggle-theme-checkbox" /> | ||
| <label id="toggle-theme-label" for="toggle-theme-checkbox"> | ||
| <span id="light-theme-indicator" title="Light mode">${LIGHT_MODE_SVG}</span> | ||
| <span id="dark-theme-indicator" title="Dark mode">${DARK_MODE_SVG}</span> | ||
| </label> | ||
| </div> | ||
| </div> | ||
| </header>`; | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI() { | ||
| return ""; | ||
| } | ||
| }; | ||
| export { | ||
| Header | ||
| }; |
| import { | ||
| colors, | ||
| htmlEscape | ||
| } from "./chunk-4L7RY2JA.js"; | ||
| import { | ||
| publicDirURL | ||
| } from "./chunk-OSUFJZHZ.js"; | ||
| import { | ||
| BaseComponent | ||
| } from "./chunk-4YEN7HVQ.js"; | ||
| // src/templates/error_stack/main.ts | ||
| import { dump, themes } from "@poppinss/dumper/html"; | ||
| import { dump as dumpCli } from "@poppinss/dumper/console"; | ||
| var CHEVIRON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" width="24" height="24" stroke-width="2"> | ||
| <path d="M6 9l6 6l6 -6"></path> | ||
| </svg>`; | ||
| var EDITORS = { | ||
| textmate: "txmt://open?url=file://%f&line=%l", | ||
| macvim: "mvim://open?url=file://%f&line=%l", | ||
| emacs: "emacs://open?url=file://%f&line=%l", | ||
| sublime: "subl://open?url=file://%f&line=%l", | ||
| phpstorm: "phpstorm://open?file=%f&line=%l", | ||
| atom: "atom://core/open/file?filename=%f&line=%l", | ||
| vscode: "vscode://file/%f:%l" | ||
| }; | ||
| var ErrorStack = class extends BaseComponent { | ||
| cssFile = new URL("./error_stack/style.css", publicDirURL); | ||
| scriptFile = new URL("./error_stack/script.js", publicDirURL); | ||
| /** | ||
| * Returns the file's relative name from the CWD | ||
| */ | ||
| #getRelativeFileName(filePath) { | ||
| return filePath.replace(`${process.cwd()}/`, ""); | ||
| } | ||
| /** | ||
| * Returns the index of the frame that should be expanded by | ||
| * default | ||
| */ | ||
| #getFirstExpandedFrameIndex(frames) { | ||
| let expandAtIndex = frames.findIndex((frame) => frame.type === "app"); | ||
| if (expandAtIndex === -1) { | ||
| expandAtIndex = frames.findIndex((frame) => frame.type === "module"); | ||
| } | ||
| return expandAtIndex; | ||
| } | ||
| /** | ||
| * Returns the link to open the file within known code | ||
| * editors | ||
| */ | ||
| #getEditorLink(ide, frame) { | ||
| const editorURL = EDITORS[ide] || ide; | ||
| if (!editorURL || frame.type === "native") { | ||
| return { | ||
| text: this.#getRelativeFileName(frame.fileName) | ||
| }; | ||
| } | ||
| return { | ||
| href: editorURL.replace("%f", frame.fileName).replace("%l", String(frame.lineNumber)), | ||
| text: this.#getRelativeFileName(frame.fileName) | ||
| }; | ||
| } | ||
| /** | ||
| * Returns the HTML fragment for the frame location | ||
| */ | ||
| #renderFrameLocation(frame, ide) { | ||
| const { text, href } = this.#getEditorLink(ide, frame); | ||
| const fileName = `<a${href ? ` href="${href}"` : ""} class="stack-frame-filepath" title="${text}"> | ||
| ${htmlEscape(text)} | ||
| </a>`; | ||
| const functionName = frame.functionName ? `<span>in <code title="${frame.functionName}"> | ||
| ${htmlEscape(frame.functionName)} | ||
| </code></span>` : ""; | ||
| const loc = `<span>at line <code>${frame.lineNumber}:${frame.columnNumber}</code></span>`; | ||
| if (frame.type !== "native" && frame.source) { | ||
| return `<button class="stack-frame-location"> | ||
| ${fileName} ${functionName} ${loc} | ||
| </button>`; | ||
| } | ||
| return `<div class="stack-frame-location"> | ||
| ${fileName} ${functionName} ${loc} | ||
| </div>`; | ||
| } | ||
| /** | ||
| * Returns HTML fragment for the stack frame | ||
| */ | ||
| async #renderStackFrame(frame, index, expandAtIndex, props) { | ||
| const label = frame.type === "app" ? '<span class="frame-label">In App</span>' : ""; | ||
| const expandedClass = expandAtIndex === index ? " expanded" : ""; | ||
| const toggleButton = frame.type !== "native" && frame.source ? `<button class="stack-frame-toggle-indicator">${CHEVIRON}</button>` : ""; | ||
| return `<li class="stack-frame stack-frame-${frame.type}${expandedClass}"> | ||
| <div class="stack-frame-contents"> | ||
| ${this.#renderFrameLocation(frame, props.ide)} | ||
| <div class="stack-frame-extras"> | ||
| ${label} | ||
| ${toggleButton} | ||
| </div> | ||
| </div> | ||
| <div class="stack-frame-source"> | ||
| ${await props.sourceCodeRenderer(props.error, frame)} | ||
| </div> | ||
| </li>`; | ||
| } | ||
| /** | ||
| * Returns the ANSI output to print the stack frame on the | ||
| * terminal | ||
| */ | ||
| async #printStackFrame(frame, index, expandAtIndex, props) { | ||
| const fileName = this.#getRelativeFileName(frame.fileName); | ||
| const loc = `${fileName}:${frame.lineNumber}:${frame.columnNumber}`; | ||
| if (index === expandAtIndex) { | ||
| const functionName2 = frame.functionName ? `at ${frame.functionName} ` : ""; | ||
| const codeSnippet = await props.sourceCodeRenderer(props.error, frame); | ||
| return ` \u2043 ${functionName2}${colors.yellow(`(${loc})`)}${codeSnippet}`; | ||
| } | ||
| if (frame.type === "native") { | ||
| const functionName2 = frame.functionName ? `at ${colors.italic(frame.functionName)} ` : ""; | ||
| return colors.dim(` \u2043 ${functionName2}(${colors.italic(loc)})`); | ||
| } | ||
| const functionName = frame.functionName ? `at ${frame.functionName} ` : ""; | ||
| return ` \u2043 ${functionName}${colors.yellow(`(${loc})`)}`; | ||
| } | ||
| /** | ||
| * The toHTML method is used to output the HTML for the | ||
| * web view | ||
| */ | ||
| async toHTML(props) { | ||
| const frames = await Promise.all( | ||
| props.error.frames.map((frame, index) => { | ||
| return this.#renderStackFrame( | ||
| frame, | ||
| index, | ||
| this.#getFirstExpandedFrameIndex(props.error.frames), | ||
| props | ||
| ); | ||
| }) | ||
| ); | ||
| return `<section> | ||
| <div class="card"> | ||
| <div class="card-heading"> | ||
| <div> | ||
| <h3 class="card-title"> | ||
| Stack Trace | ||
| </h3> | ||
| </div> | ||
| </div> | ||
| <div class="card-body"> | ||
| <div id="stack-frames-wrapper"> | ||
| <div id="stack-frames-header"> | ||
| <div id="all-frames-toggle-wrapper"> | ||
| <label id="all-frames-toggle"> | ||
| <input type="checkbox" /> | ||
| <span> View All Frames </span> | ||
| </label> | ||
| </div> | ||
| <div> | ||
| <div class="toggle-switch"> | ||
| <button id="formatted-frames-toggle" class="active"> Pretty </button> | ||
| <button id="raw-frames-toggle"> Raw </button> | ||
| </div> | ||
| </div> | ||
| </div> | ||
| <div id="stack-frames-body"> | ||
| <div id="stack-frames-formatted" class="visible"> | ||
| <ul id="stack-frames"> | ||
| ${frames.join("\n")} | ||
| </ul> | ||
| </div> | ||
| <div id="stack-frames-raw"> | ||
| ${dump(props.error.raw, { | ||
| styles: themes.cssVariables, | ||
| expand: true, | ||
| cspNonce: props.cspNonce, | ||
| inspectObjectPrototype: false, | ||
| inspectStaticMembers: false, | ||
| inspectArrayPrototype: false | ||
| })} | ||
| </div> | ||
| </div> | ||
| <div> | ||
| </div> | ||
| </div> | ||
| </section>`; | ||
| } | ||
| /** | ||
| * The toANSI method is used to output the text for the console | ||
| */ | ||
| async toANSI(props) { | ||
| const displayRaw = process.env.YOUCH_RAW; | ||
| if (displayRaw) { | ||
| const depth = Number.isNaN(Number(displayRaw)) ? 2 : Number(displayRaw); | ||
| return ` | ||
| ${colors.red("[RAW]")} | ||
| ${dumpCli(props.error.raw, { | ||
| depth, | ||
| inspectObjectPrototype: false, | ||
| inspectStaticMembers: false, | ||
| inspectArrayPrototype: false | ||
| })}`; | ||
| } | ||
| const frames = await Promise.all( | ||
| props.error.frames.map((frame, index) => { | ||
| return this.#printStackFrame( | ||
| frame, | ||
| index, | ||
| this.#getFirstExpandedFrameIndex(props.error.frames), | ||
| props | ||
| ); | ||
| }) | ||
| ); | ||
| if (frames.length) { | ||
| return ` | ||
| ${frames.join("\n")}`; | ||
| } | ||
| return ""; | ||
| } | ||
| }; | ||
| export { | ||
| ErrorStack | ||
| }; |
| import { parentPort, threadId, workerData } from "node:worker_threads"; | ||
| import { Agent } from "undici"; | ||
| import { ModuleRunner, ESModulesEvaluator } from "vite/module-runner"; | ||
| import { getSocketAddress, isSocketSupported } from "get-port-please"; | ||
| // ----- Environment runners ----- | ||
| const envs = (globalThis.__nitro_vite_envs__ ??= { | ||
| nitro: undefined, | ||
| ssr: undefined, | ||
| }); | ||
| class EnvRunner { | ||
| constructor({ name, entry }) { | ||
| this.name = name; | ||
| this.entryPath = entry; | ||
| this.entry = undefined; | ||
| this.entryError = undefined; | ||
| // Create Vite Module Runner | ||
| // https://vite.dev/guide/api-environment-runtimes.html#modulerunner | ||
| this.runnerHooks = {}; | ||
| this.runner = new ModuleRunner( | ||
| { | ||
| transport: { | ||
| connect({ onMessage, onDisconnection }) { | ||
| parentPort.on("message", (payload) => { | ||
| if (payload?.type === "custom" && payload.viteEnv === name) { | ||
| onMessage(payload); | ||
| } | ||
| }); | ||
| parentPort.on("close", onDisconnection); | ||
| }, | ||
| send(payload) { | ||
| parentPort.postMessage({ ...payload, viteEnv: name }); | ||
| }, | ||
| }, | ||
| }, | ||
| new ESModulesEvaluator(), | ||
| process.env.DEBUG ? console.debug : undefined | ||
| ); | ||
| this.reload(); | ||
| } | ||
| async reload() { | ||
| try { | ||
| this.entry = await this.runner.import(this.entryPath); | ||
| this.entryError = undefined; | ||
| } catch (error) { | ||
| console.error(error); | ||
| this.entryError = error; | ||
| } | ||
| } | ||
| async fetch(req, init) { | ||
| if (this.entryError) { | ||
| return renderError(req, this.entryError); | ||
| } | ||
| for (let i = 0; i < 5 && !(this.entry || this.entryError); i++) { | ||
| await new Promise((r) => setTimeout(r, 100 * Math.pow(2, i))); | ||
| } | ||
| if (this.entryError) { | ||
| return renderError(req, this.entryError); | ||
| } | ||
| if (!this.entry) { | ||
| throw httpError(503, `Vite environment "${this.name}" is unavailable`); | ||
| } | ||
| try { | ||
| const entryFetch = this.entry.fetch || this.entry.default?.fetch; | ||
| if (!entryFetch) { | ||
| throw httpError( | ||
| 500, | ||
| `No fetch handler exported from ${this.entryPath}` | ||
| ); | ||
| } | ||
| return await entryFetch(req, init); | ||
| } catch (error) { | ||
| return renderError(req, error); | ||
| } | ||
| } | ||
| } | ||
| // ----- RPC listeners ----- | ||
| const viteHostRequests = new Map(); | ||
| async function requestToViteHost( | ||
| name, | ||
| data, | ||
| id = Math.random().toString(16).slice(2), | ||
| timeout = 3000 | ||
| ) { | ||
| setTimeout(() => { | ||
| if (viteHostRequests.has(id)) { | ||
| viteHostRequests.delete(id); | ||
| reject(new Error(`Request to vite host timed out (${name}:${id})`)); | ||
| } | ||
| }, timeout); | ||
| let resolve, reject; | ||
| const promise = new Promise((_resolve, _reject) => { | ||
| resolve = (value) => { | ||
| viteHostRequests.delete(id); | ||
| return _resolve(value); | ||
| }; | ||
| reject = (err) => { | ||
| viteHostRequests.delete(id); | ||
| return _reject(err); | ||
| }; | ||
| }); | ||
| viteHostRequests.set(id, { resolve, reject }); | ||
| parentPort.postMessage({ | ||
| type: "custom", | ||
| event: "nitro:vite-invoke", | ||
| data: { name, id, data }, | ||
| }); | ||
| return promise; | ||
| } | ||
| parentPort.on("message", (payload) => { | ||
| if (payload?.type !== "custom") { | ||
| return; | ||
| } | ||
| switch (payload.event) { | ||
| case "nitro:vite-server-addr": { | ||
| viteServerAddr = payload.data; | ||
| break; | ||
| } | ||
| case "nitro:vite-env": { | ||
| const { name, entry } = payload.data; | ||
| if (envs[name]) { | ||
| console.error(`Vite environment "${name}" already registered!`); | ||
| } else { | ||
| envs[name] = new EnvRunner({ name, entry }); | ||
| } | ||
| break; | ||
| } | ||
| case "nitro:vite-invoke-response": { | ||
| const { id, data: response } = payload.data; | ||
| const req = viteHostRequests.get(id); | ||
| if (req) { | ||
| if (response.error) { | ||
| req.reject(response.error); | ||
| } else { | ||
| req.resolve(response.data); | ||
| } | ||
| } | ||
| break; | ||
| } | ||
| } | ||
| }); | ||
| // ----- Server ----- | ||
| async function reload() { | ||
| try { | ||
| // Apply globals | ||
| for (const [key, value] of Object.entries(workerData.globals || {})) { | ||
| globalThis[key] = value; | ||
| } | ||
| // Reload all envs | ||
| await Promise.all(Object.values(envs).map((env) => env?.reload())); | ||
| } catch (error) { | ||
| console.error(error); | ||
| } | ||
| } | ||
| // eslint-disable-next-line unicorn/prefer-top-level-await | ||
| reload(); | ||
| if (workerData.server) { | ||
| const { createServer } = await import("node:http"); | ||
| const { toNodeHandler } = await import("srvx/node"); | ||
| const server = createServer( | ||
| toNodeHandler(async (req, init) => { | ||
| const viteEnv = | ||
| init?.viteEnv || req?.headers.get("x-vite-env") || "nitro"; // TODO | ||
| const env = envs[viteEnv]; | ||
| if (!env) { | ||
| return renderError( | ||
| req, | ||
| httpError(500, `Unknown vite environment "${viteEnv}"`) | ||
| ); | ||
| } | ||
| return env.fetch(req, init); | ||
| }) | ||
| ); | ||
| server.on("upgrade", (req, socket, head) => { | ||
| const handleUpgrade = envs["nitro"]?.entry?.handleUpgrade; | ||
| handleUpgrade?.(req, socket, head); | ||
| }); | ||
| parentPort.on("message", async (message) => { | ||
| if (message?.type === "full-reload") { | ||
| await reload(); | ||
| } | ||
| }); | ||
| await listen(server); | ||
| const address = server.address(); | ||
| parentPort?.postMessage({ | ||
| event: "listen", | ||
| address: | ||
| typeof address === "string" | ||
| ? { socketPath: address } | ||
| : { host: "localhost", port: address?.port }, | ||
| }); | ||
| } | ||
| // ----- HTML Transform ----- | ||
| globalThis.__transform_html__ = async function (html) { | ||
| html = await requestToViteHost("transformHTML", html).catch((error) => { | ||
| console.warn("Failed to transform HTML via Vite:", error); | ||
| return html; | ||
| }); | ||
| return html; | ||
| }; | ||
| // ----- Error handling ----- | ||
| function httpError(status, message) { | ||
| const error = new Error(message || `HTTP Error ${status}`); | ||
| error.status = status; | ||
| error.name = "NitroViteError"; | ||
| return error; | ||
| } | ||
| async function renderError(req, error) { | ||
| const { Youch } = await import("youch"); | ||
| const youch = new Youch(); | ||
| return new Response(await youch.toHTML(error), { | ||
| status: error.status || 500, | ||
| headers: { | ||
| "Content-Type": "text/html", | ||
| "Cache-Control": "no-store, max-age=0, must-revalidate", | ||
| Pragma: "no-cache", | ||
| Expires: "0", | ||
| }, | ||
| }); | ||
| } | ||
| // ----- Internal Utils ----- | ||
| async function listen(server) { | ||
| const listenAddr = (await isSocketSupported()) | ||
| ? getSocketAddress({ | ||
| name: `nitro-vite-${threadId}`, | ||
| pid: true, | ||
| random: true, | ||
| }) | ||
| : { port: 0, host: "localhost" }; | ||
| return new Promise((resolve, reject) => { | ||
| try { | ||
| server.listen(listenAddr, () => resolve()); | ||
| } catch (error) { | ||
| reject(error); | ||
| } | ||
| }); | ||
| } | ||
| function fetchAddress(addr, input, inputInit) { | ||
| let url; | ||
| let init; | ||
| if (input instanceof Request) { | ||
| url = new URL(input.url); | ||
| init = { | ||
| method: input.method, | ||
| headers: input.headers, | ||
| body: input.body, | ||
| ...inputInit, | ||
| }; | ||
| } else { | ||
| url = new URL(input); | ||
| init = inputInit; | ||
| } | ||
| init = { | ||
| duplex: "half", | ||
| redirect: "manual", | ||
| ...init, | ||
| }; | ||
| if (addr.socketPath) { | ||
| url.protocol = "http:"; | ||
| return fetch(url, { | ||
| ...init, | ||
| ...fetchSocketOptions(addr.socketPath), | ||
| }); | ||
| } | ||
| const origin = `http://${addr.host}${addr.port ? `:${addr.port}` : ""}`; | ||
| const outURL = new URL(url.pathname + url.search, origin); | ||
| return fetch(outURL, init); | ||
| } | ||
| function fetchSocketOptions(socketPath) { | ||
| if ("Bun" in globalThis) { | ||
| // https://bun.sh/guides/http/fetch-unix | ||
| return { unix: socketPath }; | ||
| } | ||
| if ("Deno" in globalThis) { | ||
| // https://github.com/denoland/deno/pull/29154 | ||
| return { | ||
| client: Deno.createHttpClient({ | ||
| // @ts-expect-error Missing types? | ||
| transport: "unix", | ||
| path: socketPath, | ||
| }), | ||
| }; | ||
| } | ||
| // https://github.com/nodejs/undici/issues/2970 | ||
| return { | ||
| dispatcher: new Agent({ connect: { socketPath } }), | ||
| }; | ||
| } |
| type FetchableEnv = { | ||
| fetch: (request: Request) => Response | Promise<Response>; | ||
| }; | ||
| declare global { | ||
| var __nitro_vite_envs__: Record<string, FetchableEnv>; | ||
| } | ||
| export declare function fetchViteEnv(viteEnvName: string, input: RequestInfo | URL, init?: RequestInit); | ||
| export {}; |
| import { HTTPError, toRequest } from "h3"; | ||
| export function fetchViteEnv(viteEnvName, input, init) { | ||
| const envs = globalThis.__nitro_vite_envs__ || {}; | ||
| const viteEnv = envs[viteEnvName]; | ||
| if (!viteEnv) { | ||
| throw HTTPError.status(404); | ||
| } | ||
| return Promise.resolve(viteEnv.fetch(toRequest(input, init))); | ||
| } |
| export * from "h3"; |
| export * from "h3"; |
| export { $fetch } from "ofetch"; |
| export { $fetch } from "ofetch"; |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Network access
Supply chain riskThis module accesses the network.
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 5 instances
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 2 instances
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Network access
Supply chain riskThis module accesses the network.
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 10 instances
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 4 instances
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
21
10.53%175
-12.94%110
-17.29%2513331
-22.09%89
1.14%303
-0.98%62167
-20.59%+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
Updated
Updated
Updated
Updated
Updated
Updated
Updated
Updated