UNPKG

llmoptimizer

Version:

Generate an llms.txt summary of your website/docs for LLMs (framework-agnostic with Vite/Next/Nuxt/Astro/Remix helpers).

1,088 lines (1,080 loc) 194 kB
"use strict"; 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 __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/lib/next-extract.ts async function extractNextRoutes(projectRoot) { const roots = [ { dir: import_node_path.default.join(projectRoot, "pages"), source: "pages" }, { dir: import_node_path.default.join(projectRoot, "src", "pages"), source: "pages" }, { dir: import_node_path.default.join(projectRoot, "app"), source: "app" }, { dir: import_node_path.default.join(projectRoot, "src", "app"), source: "app" } ]; const out = []; for (const root of roots) { try { const st = await import_promises.default.stat(root.dir); if (!st.isDirectory()) continue; } catch { continue; } if (root.source === "pages") { const files = await (0, import_globby.globby)(["**/*.{js,jsx,ts,tsx,md,mdx}"], { cwd: root.dir, dot: false }); for (const rel of files) { if (/^(?:api\/|_)/.test(rel)) continue; if (rel.split("/").some((seg) => seg.startsWith("_"))) continue; const route = fileToPagesRoute(rel); const abs = import_node_path.default.join(root.dir, rel); const meta = await safeReadMeta(abs); const dyn = /\[.*?\]/.test(rel); const params = extractParamsFromPattern(route); out.push({ route, file: rel, absPath: abs, type: "page", source: root.source, dynamic: dyn, params, metadata: meta }); } } else { const pages = await (0, import_globby.globby)(["**/page.{js,jsx,ts,tsx,md,mdx}"], { cwd: root.dir, dot: false }); const layouts = await (0, import_globby.globby)(["**/layout.{js,jsx,ts,tsx}"], { cwd: root.dir, dot: false }); for (const rel of pages) { if (/^(?:api\/)/.test(rel)) continue; const route = appFileToRoute(rel); const abs = import_node_path.default.join(root.dir, rel); const meta = await safeReadMeta(abs); const dyn = /\[.*?\]/.test(rel); const params = extractParamsFromPattern(route); out.push({ route, file: rel, absPath: abs, type: "page", source: root.source, dynamic: dyn, params, metadata: meta }); } for (const rel of layouts) { const route = appFileToRoute(rel); const abs = import_node_path.default.join(root.dir, rel); const meta = await safeReadMeta(abs); out.push({ route, file: rel, absPath: abs, type: "layout", source: root.source, dynamic: false, params: [], metadata: meta }); } } } const byRoute = /* @__PURE__ */ new Map(); for (const r of out) { const existing = byRoute.get(r.route); if (!existing) { byRoute.set(r.route, r); continue; } if (existing.source === "pages" && r.source === "app" && r.type === "page") { byRoute.set(r.route, r); } } const locales = await detectLocales(projectRoot); return { routes: Array.from(byRoute.values()), locales }; } function fileToPagesRoute(filePath) { let p = filePath.replace(/\.(jsx?|tsx?|mdx?)$/i, ""); p = p.replace(/\/(?:index)$/i, ""); p = p.replace(/\[\[?\.\.\.(.+?)\]?\]/g, ":$1*").replace(/\[(.+?)\]/g, ":$1"); p = "/" + p.replace(/^\/+/, ""); return p === "/index" || p === "/" ? "/" : p; } function appFileToRoute(filePath) { let dir = import_node_path.default.dirname(filePath).replace(/\\/g, "/"); if (dir === "." || dir === "/") return "/"; dir = dir.split("/").filter((seg) => seg && !seg.startsWith("@")).map((seg) => seg.replace(/\(.+?\)/g, "")).filter(Boolean).join("/"); dir = dir.replace(/\(\.\.\.\)|\(\.\.\)|\(\.\)/g, ""); dir = dir.replace(/\[\[?\.\.\.(.+?)\]?\]/g, ":$1*").replace(/\[(.+?)\]/g, ":$1"); const route = "/" + dir.replace(/\/+/, ""); return route.replace(/\/+/, "/").replace(/\/$/, "") || "/"; } function extractParamsFromPattern(route) { const m = route.match(/:([A-Za-z0-9_]+)\*?/g); return m ? Array.from(new Set(m.map((s) => s.replace(/^:/, "").replace(/\*$/, "")))) : []; } async function safeReadMeta(absPath) { try { const content = await import_promises.default.readFile(absPath, "utf8"); return extractMetadata(content); } catch { return void 0; } } function extractMetadata(content) { const metadata = {}; const metaBlock = content.match(/export\s+const\s+metadata\s*=\s*\{([\s\S]*?)\}/m); if (metaBlock) { const title = metaBlock[1].match(/title\s*:\s*(['\"][^'\"]+['\"])|title\s*:\s*`([^`]+)`/); const desc = metaBlock[1].match(/description\s*:\s*(['\"][^'\"]+['\"])|description\s*:\s*`([^`]+)`/); if (title) metadata.title = (title[2] || title[1] || "").replace(/^['\"]|['\"]$/g, ""); if (desc) metadata.description = (desc[2] || desc[1] || "").replace(/^['\"]|['\"]$/g, ""); } else { const titleTag = content.match(/<title[^>]*>([^<]+)<\/title>/i); const titleProp = content.match(/title:\s*['\"]([^'\"]+)['\"]/); const descProp = content.match(/description:\s*['\"]([^'\"]+)['\"]/); if (titleTag) metadata.title = titleTag[1]; else if (titleProp) metadata.title = titleProp[1]; if (descProp) metadata.description = descProp[1]; } const hasDefault = /export\s+default/.test(content); const named = Array.from(content.matchAll(/export\s+(?:const|function|class)\s+(\w+)/g)).map((m) => m[1]); metadata.exports = { default: hasDefault, named }; return metadata; } async function detectLocales(projectRoot) { const locales = /* @__PURE__ */ new Set(); try { const dir = import_node_path.default.join(projectRoot, "public", "locales"); const items = await import_promises.default.readdir(dir, { withFileTypes: true }); for (const it of items) if (it.isDirectory()) locales.add(it.name); } catch { } const cfgFiles = ["next.config.js", "next.config.mjs", "next.config.cjs", "next.config.ts"]; for (const f of cfgFiles) { try { const src = await import_promises.default.readFile(import_node_path.default.join(projectRoot, f), "utf8"); const m = src.match(/i18n\s*:\s*\{[\s\S]*?locales\s*:\s*\[([^\]]+)\]/m); if (m) { const arr = m[1]; const re = /['\"]([a-zA-Z0-9-]+)['\"]/g; let mm; while (mm = re.exec(arr)) locales.add(mm[1]); } } catch { } } return locales.size ? Array.from(locales) : void 0; } var import_promises, import_node_path, import_globby; var init_next_extract = __esm({ "src/lib/next-extract.ts"() { "use strict"; import_promises = __toESM(require("fs/promises"), 1); import_node_path = __toESM(require("path"), 1); import_globby = require("globby"); } }); // src/adapters/next.ts var import_promises2, import_node_path2, import_globby2, NextAdapter; var init_next = __esm({ "src/adapters/next.ts"() { "use strict"; import_promises2 = __toESM(require("fs/promises"), 1); import_node_path2 = __toESM(require("path"), 1); import_globby2 = require("globby"); init_next_extract(); NextAdapter = { name: "nextjs", async detect(ctx) { try { const pkg = JSON.parse(await import_promises2.default.readFile(import_node_path2.default.join(ctx.projectRoot, "package.json"), "utf8")); return Boolean(pkg.dependencies?.next || pkg.devDependencies?.next); } catch { return false; } }, async routes(ctx) { const extracted = await extractNextRoutes(ctx.projectRoot); const routes = /* @__PURE__ */ new Set(); for (const r of extracted.routes) { if (r.type === "page") routes.add(r.route || "/"); } return { routes: Array.from(routes), buildDirs: [".next/export", ".next/server/pages", ".next/server/app", "out"] }; }, async discoverParams(ctx) { const params = {}; try { const extracted = await extractNextRoutes(ctx.projectRoot); if (extracted.locales?.length) { params["lang"] = extracted.locales; params["locale"] = extracted.locales; } const dynNames = /* @__PURE__ */ new Set(); for (const r of extracted.routes) { r.params?.forEach((p) => dynNames.add(p)); } for (const name of dynNames) { if (name === "slug") params[name] = ["welcome", "hello-world"]; else if (name === "id") params[name] = ["1", "2", "42"]; else params[name] = ["sample"]; } } catch { } params["id"] = Array.from(/* @__PURE__ */ new Set([...params["id"] || [], "1", "2", "42"])); params["slug"] = Array.from(/* @__PURE__ */ new Set([...params["slug"] || [], "welcome", "hello-world"])); return params; }, async discoverRouteParams(ctx) { const slugSamples = /* @__PURE__ */ new Set(["welcome", "hello-world"]); const langSamples = /* @__PURE__ */ new Set(); try { const blogFiles = await (0, import_globby2.globby)([ "content/blog/*.*", "src/content/blog/*.*", "content/posts/*.*", "src/content/posts/*.*", "pages/blog/*.*", "src/pages/blog/*.*", "app/blog/*.*", "src/app/blog/*.*", "app/blog/**/page.*", "src/app/blog/**/page.*" ], { cwd: ctx.projectRoot }); for (const f of blogFiles) { const base = import_node_path2.default.basename(f, import_node_path2.default.extname(f)); if (base && base !== "index") slugSamples.add(base); } const extracted = await extractNextRoutes(ctx.projectRoot); if (extracted.locales?.length) extracted.locales.forEach((l) => langSamples.add(l)); } catch { } const routeParams = {}; routeParams["/blog/:slug"] = { slug: Array.from(slugSamples) }; if (langSamples.size) { routeParams["/:lang"] = { lang: Array.from(langSamples) }; routeParams["/:lang/*"] = { lang: Array.from(langSamples) }; routeParams["/:locale"] = { locale: Array.from(langSamples) }; routeParams["/:locale/*"] = { locale: Array.from(langSamples) }; } return routeParams; } }; } }); // src/adapters/nuxt.ts var import_globby3, import_node_path3, import_promises3, NuxtAdapter; var init_nuxt = __esm({ "src/adapters/nuxt.ts"() { "use strict"; import_globby3 = require("globby"); import_node_path3 = __toESM(require("path"), 1); import_promises3 = __toESM(require("fs/promises"), 1); NuxtAdapter = { name: "nuxt", async detect(ctx) { try { const pkg = JSON.parse(await import_promises3.default.readFile(import_node_path3.default.join(ctx.projectRoot, "package.json"), "utf8")); return Boolean(pkg.dependencies?.nuxt || pkg.devDependencies?.nuxt); } catch { return false; } }, async routes(ctx) { const roots = ["pages", "src/pages"]; const routes = /* @__PURE__ */ new Set(); for (const r of roots) { const dir = import_node_path3.default.join(ctx.projectRoot, r); const files = await (0, import_globby3.globby)(["**/*.vue"], { cwd: dir, dot: false }); for (const f of files) { const withoutExt = f.replace(/\.vue$/i, ""); const parts = withoutExt.split(import_node_path3.default.sep); if (parts[parts.length - 1] === "index") parts.pop(); const route = "/" + parts.map( (p) => p.replace(/\[(\.\.\.)?(.+?)\]/g, (_m, dots, name) => dots ? `:${name}*` : `:${name}`) ).join("/"); routes.add(route || "/"); } } return { routes: Array.from(routes), buildDirs: [".output/public", "dist"] }; }, async discoverParams(ctx) { const params = {}; const locales = /* @__PURE__ */ new Set(); const cfgFiles = ["nuxt.config.ts", "nuxt.config.js", "nuxt.config.mjs", "nuxt.config.cjs"]; for (const f of cfgFiles) { try { const src = await import_promises3.default.readFile(import_node_path3.default.join(ctx.projectRoot, f), "utf8"); const m = src.match(/i18n\s*:\s*\{[\s\S]*?locales\s*:\s*\[([^\]]+)\]/m); if (m) { const arr = m[1]; const re = /['\"]([a-zA-Z0-9-]+)['\"]/g; let mm; while (mm = re.exec(arr)) locales.add(mm[1]); } } catch { } } try { const locDir = import_node_path3.default.join(ctx.projectRoot, "locales"); const items = await import_promises3.default.readdir(locDir); for (const it of items) { const base = import_node_path3.default.basename(it, import_node_path3.default.extname(it)); if (base) locales.add(base); } } catch { } if (locales.size) { params["lang"] = Array.from(locales); params["locale"] = Array.from(locales); } const slugs = /* @__PURE__ */ new Set(["welcome", "hello-world"]); try { const files = await (0, import_globby3.globby)([ "content/**/*.{md,mdx,markdown,mdoc}", "src/content/**/*.{md,mdx,markdown,mdoc}", "content/blog/*.*", "src/content/blog/*.*", "pages/blog/*.*", "src/pages/blog/*.*" ], { cwd: ctx.projectRoot }); for (const f of files) { const base = import_node_path3.default.basename(f, import_node_path3.default.extname(f)); if (base && base !== "index") slugs.add(base); } } catch { } params["slug"] = Array.from(slugs); params["id"] = ["1", "2", "42"]; return params; }, async discoverRouteParams(ctx) { const routeParams = {}; const samples = await this.discoverParams(ctx).catch(() => ({})); if (samples?.lang?.length) { routeParams["/:lang"] = { lang: samples.lang }; routeParams["/:lang/*"] = { lang: samples.lang }; } if (samples?.locale?.length) { routeParams["/:locale"] = { locale: samples.locale }; routeParams["/:locale/*"] = { locale: samples.locale }; } if (samples?.slug?.length) { routeParams["/blog/:slug"] = { slug: samples.slug }; } return routeParams; } }; } }); // src/adapters/astro.ts var import_globby4, import_node_path4, import_promises4, AstroAdapter; var init_astro = __esm({ "src/adapters/astro.ts"() { "use strict"; import_globby4 = require("globby"); import_node_path4 = __toESM(require("path"), 1); import_promises4 = __toESM(require("fs/promises"), 1); AstroAdapter = { name: "astro", async detect(ctx) { try { const pkg = JSON.parse(await import_promises4.default.readFile(import_node_path4.default.join(ctx.projectRoot, "package.json"), "utf8")); return Boolean(pkg.dependencies?.astro || pkg.devDependencies?.astro); } catch { return false; } }, async routes(ctx) { const roots = ["src/pages"]; const routes = /* @__PURE__ */ new Set(); for (const r of roots) { const dir = import_node_path4.default.join(ctx.projectRoot, r); const files = await (0, import_globby4.globby)(["**/*.{astro,md,mdx}"], { cwd: dir, dot: false }); for (const f of files) { const withoutExt = f.replace(/\.(astro|mdx?|md)$/i, ""); const parts = withoutExt.split(import_node_path4.default.sep); if (parts[parts.length - 1] === "index") parts.pop(); const route = "/" + parts.map((p) => p.replace(/\[(\.\.\.)?(.+?)\]/g, (_m, dots, name) => dots ? `:${name}*` : `:${name}`)).join("/"); routes.add(route || "/"); } } return { routes: Array.from(routes), buildDirs: ["dist"] }; }, async discoverRouteParams(ctx) { const slugSamples = /* @__PURE__ */ new Set(["welcome", "getting-started"]); try { const blogFiles = await (0, import_globby4.globby)(["src/pages/blog/*.{md,mdx,astro}"], { cwd: ctx.projectRoot }); for (const f of blogFiles) { const base = import_node_path4.default.basename(f, import_node_path4.default.extname(f)); if (base && base !== "index") slugSamples.add(base); } } catch { } return { "/blog/:slug": { slug: Array.from(slugSamples) } }; } }; } }); // src/adapters/remix.ts function remixFileToRoute(rel) { const withoutExt = rel.replace(/\.(tsx|ts|jsx|js|md|mdx)$/i, ""); const withSlashes = withoutExt.replace(/\./g, "/"); const parts = withSlashes.split(import_node_path5.default.sep).map((seg) => seg.replace(/^_/, "")); if (parts[parts.length - 1] === "index" || parts[parts.length - 1] === "") parts.pop(); const mapped = parts.map((p) => p.replace(/\$(\w+)/g, (_m, n) => `:${n}`)); const route = "/" + mapped.filter(Boolean).join("/"); return route || "/"; } var import_globby5, import_node_path5, import_promises5, RemixAdapter; var init_remix = __esm({ "src/adapters/remix.ts"() { "use strict"; import_globby5 = require("globby"); import_node_path5 = __toESM(require("path"), 1); import_promises5 = __toESM(require("fs/promises"), 1); RemixAdapter = { name: "remix", async detect(ctx) { try { const pkg = JSON.parse(await import_promises5.default.readFile(import_node_path5.default.join(ctx.projectRoot, "package.json"), "utf8")); return Boolean( pkg.dependencies?.["@remix-run/react"] || pkg.devDependencies?.["@remix-run/react"] || pkg.dependencies?.remix || pkg.devDependencies?.remix ); } catch { return false; } }, async routes(ctx) { const roots = ["app/routes"]; const routes = /* @__PURE__ */ new Set(); for (const r of roots) { const dir = import_node_path5.default.join(ctx.projectRoot, r); const files = await (0, import_globby5.globby)(["**/*.{tsx,ts,jsx,js,md,mdx}"], { cwd: dir, dot: false }); for (const f of files) { routes.add(remixFileToRoute(f)); } } return { routes: Array.from(routes), buildDirs: ["public"] }; }, async discoverParams(ctx) { const params = {}; try { const dir = import_node_path5.default.join(ctx.projectRoot, "app", "routes"); const files = await (0, import_globby5.globby)(["**/*.{tsx,ts,jsx,js,md,mdx}"], { cwd: dir, dot: false }); const names = /* @__PURE__ */ new Set(); for (const f of files) { const route = remixFileToRoute(f); const mm = route.match(/:([A-Za-z0-9_]+)/g); mm?.forEach((m) => names.add(m.slice(1))); } for (const n of names) { if (n === "slug") params[n] = ["welcome", "hello-world"]; else if (n === "id") params[n] = ["1", "2", "42"]; else params[n] = ["sample"]; } } catch { } const slugSet = /* @__PURE__ */ new Set(["welcome", "hello-world"]); try { const blogFiles = await (0, import_globby5.globby)(["app/routes/blog/*.*", "app/routes/blog/**/_index.*"], { cwd: ctx.projectRoot }); for (const f of blogFiles) { const base = import_node_path5.default.basename(f, import_node_path5.default.extname(f)); if (base && base !== "index" && !base.startsWith("_")) slugSet.add(base); } } catch { } params["slug"] = Array.from(slugSet); return params; }, async discoverRouteParams(ctx) { const routeParams = {}; const samples = await this.discoverParams(ctx).catch(() => ({})); if (samples?.slug?.length) routeParams["/blog/:slug"] = { slug: samples.slug }; return routeParams; } }; } }); // src/adapters/sveltekit.ts function toRouteFromRoutesDir(rel) { rel = rel.replace(/^\/+/, ""); const parts = rel.split(import_node_path6.default.sep); if (/^\+page(\.|$)/.test(parts[parts.length - 1]) || /^\+layout(\.|$)/.test(parts[parts.length - 1])) { parts.pop(); } const mapped = parts.map( (seg) => seg.replace(/\[(\.\.\.)?(.+?)\]/g, (_m, dots, name) => dots ? `:${name}*` : `:${name}`).replace(/^\(.*\)$/, "") // group folders become empty ); const route = "/" + mapped.filter(Boolean).join("/"); return route || "/"; } var import_globby6, import_node_path6, import_promises6, SvelteKitAdapter; var init_sveltekit = __esm({ "src/adapters/sveltekit.ts"() { "use strict"; import_globby6 = require("globby"); import_node_path6 = __toESM(require("path"), 1); import_promises6 = __toESM(require("fs/promises"), 1); SvelteKitAdapter = { name: "sveltekit", async detect(ctx) { try { const pkg = JSON.parse(await import_promises6.default.readFile(import_node_path6.default.join(ctx.projectRoot, "package.json"), "utf8")); return Boolean(pkg.dependencies?.["@sveltejs/kit"] || pkg.devDependencies?.["@sveltejs/kit"]); } catch { return false; } }, async routes(ctx) { const dir = import_node_path6.default.join(ctx.projectRoot, "src/routes"); const files = await (0, import_globby6.globby)(["**/*", "!**/*.d.ts"], { cwd: dir, dot: false }); const routes = /* @__PURE__ */ new Set(); for (const f of files) { if (!/\+page\.|\.svelte$/.test(f)) continue; routes.add(toRouteFromRoutesDir(f)); } return { routes: Array.from(routes), buildDirs: ["build"] }; }, async discoverParams(ctx) { const params = {}; try { const dir = import_node_path6.default.join(ctx.projectRoot, "src", "routes"); const files = await (0, import_globby6.globby)(["**/*", "!**/*.d.ts"], { cwd: dir, dot: false }); const names = /* @__PURE__ */ new Set(); for (const f of files) { const route = toRouteFromRoutesDir(f); const mm = route.match(/:([A-Za-z0-9_]+)/g); mm?.forEach((m) => names.add(m.slice(1))); } for (const n of names) { if (n === "slug") params[n] = ["welcome", "hello-world"]; else if (n === "id") params[n] = ["1", "2", "42"]; else params[n] = ["sample"]; } } catch { } const slugSet = /* @__PURE__ */ new Set(["welcome", "hello-world"]); try { const blog = await (0, import_globby6.globby)(["src/routes/blog/*", "src/routes/blog/**/+page.*"], { cwd: ctx.projectRoot }); for (const f of blog) { const base = import_node_path6.default.basename(f, import_node_path6.default.extname(f)); if (base && base !== "index" && !base.startsWith("+")) slugSet.add(base); } } catch { } params["slug"] = Array.from(slugSet); return params; }, async discoverRouteParams(ctx) { const routeParams = {}; const samples = await this.discoverParams(ctx).catch(() => ({})); if (samples?.slug?.length) routeParams["/blog/:slug"] = { slug: samples.slug }; return routeParams; } }; } }); // node_modules/esbuild/lib/main.js var require_main = __commonJS({ "node_modules/esbuild/lib/main.js"(exports2, module2) { "use strict"; var __defProp2 = Object.defineProperty; var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames2 = Object.getOwnPropertyNames; var __hasOwnProp2 = Object.prototype.hasOwnProperty; var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; var __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod); var node_exports = {}; __export2(node_exports, { analyzeMetafile: () => analyzeMetafile, analyzeMetafileSync: () => analyzeMetafileSync, build: () => build, buildSync: () => buildSync, context: () => context, default: () => node_default, formatMessages: () => formatMessages, formatMessagesSync: () => formatMessagesSync, initialize: () => initialize, stop: () => stop, transform: () => transform, transformSync: () => transformSync, version: () => version }); module2.exports = __toCommonJS2(node_exports); function encodePacket(packet) { let visit = (value) => { if (value === null) { bb.write8(0); } else if (typeof value === "boolean") { bb.write8(1); bb.write8(+value); } else if (typeof value === "number") { bb.write8(2); bb.write32(value | 0); } else if (typeof value === "string") { bb.write8(3); bb.write(encodeUTF8(value)); } else if (value instanceof Uint8Array) { bb.write8(4); bb.write(value); } else if (value instanceof Array) { bb.write8(5); bb.write32(value.length); for (let item of value) { visit(item); } } else { let keys = Object.keys(value); bb.write8(6); bb.write32(keys.length); for (let key of keys) { bb.write(encodeUTF8(key)); visit(value[key]); } } }; let bb = new ByteBuffer(); bb.write32(0); bb.write32(packet.id << 1 | +!packet.isRequest); visit(packet.value); writeUInt32LE(bb.buf, bb.len - 4, 0); return bb.buf.subarray(0, bb.len); } function decodePacket(bytes) { let visit = () => { switch (bb.read8()) { case 0: return null; case 1: return !!bb.read8(); case 2: return bb.read32(); case 3: return decodeUTF8(bb.read()); case 4: return bb.read(); case 5: { let count = bb.read32(); let value2 = []; for (let i = 0; i < count; i++) { value2.push(visit()); } return value2; } case 6: { let count = bb.read32(); let value2 = {}; for (let i = 0; i < count; i++) { value2[decodeUTF8(bb.read())] = visit(); } return value2; } default: throw new Error("Invalid packet"); } }; let bb = new ByteBuffer(bytes); let id = bb.read32(); let isRequest = (id & 1) === 0; id >>>= 1; let value = visit(); if (bb.ptr !== bytes.length) { throw new Error("Invalid packet"); } return { id, isRequest, value }; } var ByteBuffer = class { constructor(buf = new Uint8Array(1024)) { this.buf = buf; this.len = 0; this.ptr = 0; } _write(delta) { if (this.len + delta > this.buf.length) { let clone = new Uint8Array((this.len + delta) * 2); clone.set(this.buf); this.buf = clone; } this.len += delta; return this.len - delta; } write8(value) { let offset = this._write(1); this.buf[offset] = value; } write32(value) { let offset = this._write(4); writeUInt32LE(this.buf, value, offset); } write(bytes) { let offset = this._write(4 + bytes.length); writeUInt32LE(this.buf, bytes.length, offset); this.buf.set(bytes, offset + 4); } _read(delta) { if (this.ptr + delta > this.buf.length) { throw new Error("Invalid packet"); } this.ptr += delta; return this.ptr - delta; } read8() { return this.buf[this._read(1)]; } read32() { return readUInt32LE(this.buf, this._read(4)); } read() { let length = this.read32(); let bytes = new Uint8Array(length); let ptr = this._read(bytes.length); bytes.set(this.buf.subarray(ptr, ptr + length)); return bytes; } }; var encodeUTF8; var decodeUTF8; var encodeInvariant; if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") { let encoder = new TextEncoder(); let decoder = new TextDecoder(); encodeUTF8 = (text) => encoder.encode(text); decodeUTF8 = (bytes) => decoder.decode(bytes); encodeInvariant = 'new TextEncoder().encode("")'; } else if (typeof Buffer !== "undefined") { encodeUTF8 = (text) => Buffer.from(text); decodeUTF8 = (bytes) => { let { buffer, byteOffset, byteLength } = bytes; return Buffer.from(buffer, byteOffset, byteLength).toString(); }; encodeInvariant = 'Buffer.from("")'; } else { throw new Error("No UTF-8 codec found"); } if (!(encodeUTF8("") instanceof Uint8Array)) throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false This indicates that your JavaScript environment is broken. You cannot use esbuild in this environment because esbuild relies on this invariant. This is not a problem with esbuild. You need to fix your environment instead. `); function readUInt32LE(buffer, offset) { return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24; } function writeUInt32LE(buffer, value, offset) { buffer[offset++] = value; buffer[offset++] = value >> 8; buffer[offset++] = value >> 16; buffer[offset++] = value >> 24; } var quote = JSON.stringify; var buildLogLevelDefault = "warning"; var transformLogLevelDefault = "silent"; function validateAndJoinStringArray(values, what) { const toJoin = []; for (const value of values) { validateStringValue(value, what); if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`); toJoin.push(value); } return toJoin.join(","); } var canBeAnything = () => null; var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean"; var mustBeString = (value) => typeof value === "string" ? null : "a string"; var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object"; var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer"; var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number"; var mustBeFunction = (value) => typeof value === "function" ? null : "a function"; var mustBeArray = (value) => Array.isArray(value) ? null : "an array"; var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings"; var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object"; var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object"; var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module"; var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null"; var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean"; var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object"; var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings"; var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array"; var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL"; function getFlag(object, keys, key, mustBeFn) { let value = object[key]; keys[key + ""] = true; if (value === void 0) return void 0; let mustBe = mustBeFn(value); if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`); return value; } function checkForInvalidFlags(object, keys, where) { for (let key in object) { if (!(key in keys)) { throw new Error(`Invalid option ${where}: ${quote(key)}`); } } } function validateInitializeOptions(options) { let keys = /* @__PURE__ */ Object.create(null); let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL); let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule); let worker = getFlag(options, keys, "worker", mustBeBoolean); checkForInvalidFlags(options, keys, "in initialize() call"); return { wasmURL, wasmModule, worker }; } function validateMangleCache(mangleCache) { let validated; if (mangleCache !== void 0) { validated = /* @__PURE__ */ Object.create(null); for (let key in mangleCache) { let value = mangleCache[key]; if (typeof value === "string" || value === false) { validated[key] = value; } else { throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`); } } } return validated; } function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) { let color = getFlag(options, keys, "color", mustBeBoolean); let logLevel = getFlag(options, keys, "logLevel", mustBeString); let logLimit = getFlag(options, keys, "logLimit", mustBeInteger); if (color !== void 0) flags.push(`--color=${color}`); else if (isTTY2) flags.push(`--color=true`); flags.push(`--log-level=${logLevel || logLevelDefault}`); flags.push(`--log-limit=${logLimit || 0}`); } function validateStringValue(value, what, key) { if (typeof value !== "string") { throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`); } return value; } function pushCommonFlags(flags, options, keys) { let legalComments = getFlag(options, keys, "legalComments", mustBeString); let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString); let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean); let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings); let format = getFlag(options, keys, "format", mustBeString); let globalName = getFlag(options, keys, "globalName", mustBeString); let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp); let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp); let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean); let minify = getFlag(options, keys, "minify", mustBeBoolean); let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean); let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean); let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean); let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger); let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings); let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings); let charset = getFlag(options, keys, "charset", mustBeString); let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean); let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean); let jsx = getFlag(options, keys, "jsx", mustBeString); let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString); let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString); let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString); let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean); let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean); let define = getFlag(options, keys, "define", mustBeObject); let logOverride = getFlag(options, keys, "logOverride", mustBeObject); let supported = getFlag(options, keys, "supported", mustBeObject); let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings); let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean); let platform = getFlag(options, keys, "platform", mustBeString); let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject); let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings); if (legalComments) flags.push(`--legal-comments=${legalComments}`); if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`); if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`); if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`); if (format) flags.push(`--format=${format}`); if (globalName) flags.push(`--global-name=${globalName}`); if (platform) flags.push(`--platform=${platform}`); if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`); if (minify) flags.push("--minify"); if (minifySyntax) flags.push("--minify-syntax"); if (minifyWhitespace) flags.push("--minify-whitespace"); if (minifyIdentifiers) flags.push("--minify-identifiers"); if (lineLimit) flags.push(`--line-limit=${lineLimit}`); if (charset) flags.push(`--charset=${charset}`); if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`); if (ignoreAnnotations) flags.push(`--ignore-annotations`); if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`); if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`); if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`); if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`); if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`); if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`); if (jsx) flags.push(`--jsx=${jsx}`); if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`); if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`); if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`); if (jsxDev) flags.push(`--jsx-dev`); if (jsxSideEffects) flags.push(`--jsx-side-effects`); if (define) { for (let key in define) { if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`); flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`); } } if (logOverride) { for (let key in logOverride) { if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`); flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`); } } if (supported) { for (let key in supported) { if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`); const value = supported[key]; if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`); flags.push(`--supported:${key}=${value}`); } } if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`); if (keepNames) flags.push(`--keep-names`); } function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) { var _a2; let flags = []; let entries = []; let keys = /* @__PURE__ */ Object.create(null); let stdinContents = null; let stdinResolveDir = null; pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); pushCommonFlags(flags, options, keys); let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); let bundle = getFlag(options, keys, "bundle", mustBeBoolean); let splitting = getFlag(options, keys, "splitting", mustBeBoolean); let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean); let metafile = getFlag(options, keys, "metafile", mustBeBoolean); let outfile = getFlag(options, keys, "outfile", mustBeString); let outdir = getFlag(options, keys, "outdir", mustBeString); let outbase = getFlag(options, keys, "outbase", mustBeString); let tsconfig = getFlag(options, keys, "tsconfig", mustBeString); let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings); let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings); let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings); let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings); let external = getFlag(options, keys, "external", mustBeArrayOfStrings); let packages = getFlag(options, keys, "packages", mustBeString); let alias = getFlag(options, keys, "alias", mustBeObject); let loader = getFlag(options, keys, "loader", mustBeObject); let outExtension = getFlag(options, keys, "outExtension", mustBeObject); let publicPath = getFlag(options, keys, "publicPath", mustBeString); let entryNames = getFlag(options, keys, "entryNames", mustBeString); let chunkNames = getFlag(options, keys, "chunkNames", mustBeString); let assetNames = getFlag(options, keys, "assetNames", mustBeString); let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings); let banner = getFlag(options, keys, "banner", mustBeObject); let footer = getFlag(options, keys, "footer", mustBeObject); let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints); let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString); let stdin = getFlag(options, keys, "stdin", mustBeObject); let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault; let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean); let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject); keys.plugins = true; checkForInvalidFlags(options, keys, `in ${callName}() call`); if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`); if (bundle) flags.push("--bundle"); if (allowOverwrite) flags.push("--allow-overwrite"); if (splitting) flags.push("--splitting"); if (preserveSymlinks) flags.push("--preserve-symlinks"); if (metafile) flags.push(`--metafile`); if (outfile) flags.push(`--outfile=${outfile}`); if (outdir) flags.push(`--outdir=${outdir}`); if (outbase) flags.push(`--outbase=${outbase}`); if (tsconfig) flags.push(`--tsconfig=${tsconfig}`); if (packages) flags.push(`--packages=${packages}`); if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`); if (publicPath) flags.push(`--public-path=${publicPath}`); if (entryNames) flags.push(`--entry-names=${entryNames}`); if (chunkNames) flags.push(`--chunk-names=${chunkNames}`); if (assetNames) flags.push(`--asset-names=${assetNames}`); if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`); if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`); if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`); if (alias) { for (let old in alias) { if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`); flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`); } } if (banner) { for (let type in banner) { if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`); flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`); } } if (footer) { for (let type in footer) { if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`); flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`); } } if (inject) for (let path32 of inject) flags.push(`--inject:${validateStringValue(path32, "inject")}`); if (loader) { for (let ext in loader) { if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`); flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`); } } if (outExtension) { for (let ext in outExtension) { if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`); flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`); } } if (entryPoints) { if (Array.isArray(entryPoints)) { for (let i = 0, n = entryPoints.length; i < n; i++) { let entryPoint = entryPoints[i]; if (typeof entryPoint === "object" && entryPoint !== null) { let entryPointKeys = /* @__PURE__ */ Object.create(null); let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString); let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString); checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i); if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i); if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i); entries.push([output, input]); } else { entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]); } } } else { for (let key in entryPoints) { entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]); } } } if (stdin) { let stdinKeys = /* @__PURE__ */ Object.create(null); let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array); let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString); let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString); let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString); checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object'); if (sourcefile) flags.push(`--sourcefile=${sourcefile}`); if (loader2) flags.push(`--loader=${loader2}`); if (resolveDir) stdinResolveDir = resolveDir; if (typeof contents === "string") stdinContents = encodeUTF8(contents); else if (contents instanceof Uint8Array) stdin