import { t as defaultSeed } from "../default-Cyi4aAxu.mjs";
import { createRequire } from "node:module";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { readFileSync } from "node:fs";

//#region src/astro/storage/adapters.ts
/**
* S3-compatible storage adapter
*
* Works with AWS S3, Cloudflare R2 (via S3 API), Minio, etc.
*
* @example
* ```ts
* storage: s3({
*   endpoint: "https://xxx.r2.cloudflarestorage.com",
*   bucket: "media",
*   accessKeyId: process.env.R2_ACCESS_KEY_ID!,
*   secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
*   publicUrl: "https://cdn.example.com", // optional CDN
* })
* ```
*/
function s3(config) {
	return {
		entrypoint: "emdash/storage/s3",
		config
	};
}
/**
* Local filesystem storage adapter
*
* For development and testing. Stores files in a local directory.
* Does NOT support signed upload URLs.
*
* @example
* ```ts
* storage: local({
*   directory: "./uploads",
*   baseUrl: "/_emdash/api/media/file",
* })
* ```
*/
function local(config) {
	return {
		entrypoint: "emdash/storage/local",
		config
	};
}

//#endregion
//#region src/astro/integration/routes.ts
/**
* Route Injection
*
* Defines and injects all EmDash routes into the Astro application.
*/
/**
* Resolve path to a route file in the package
* Uses Node.js APIs - only call at build time
*/
function resolveRoute(route) {
	const require = createRequire(import.meta.url);
	const __dirname = dirname(fileURLToPath(import.meta.url));
	try {
		return require.resolve(`emdash/routes/${route}`);
	} catch {
		return resolve(__dirname, "../routes", route);
	}
}
/**
* Injects all core EmDash routes.
*/
function injectCoreRoutes(injectRoute) {
	injectRoute({
		pattern: "/_emdash/admin/[...path]",
		entrypoint: resolveRoute("admin.astro")
	});
	injectRoute({
		pattern: "/_emdash/api/manifest",
		entrypoint: resolveRoute("api/manifest.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/dashboard",
		entrypoint: resolveRoute("api/dashboard.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]",
		entrypoint: resolveRoute("api/content/[collection]/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]",
		entrypoint: resolveRoute("api/content/[collection]/[id].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]/revisions",
		entrypoint: resolveRoute("api/content/[collection]/[id]/revisions.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]/preview-url",
		entrypoint: resolveRoute("api/content/[collection]/[id]/preview-url.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/trash",
		entrypoint: resolveRoute("api/content/[collection]/trash.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]/restore",
		entrypoint: resolveRoute("api/content/[collection]/[id]/restore.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]/permanent",
		entrypoint: resolveRoute("api/content/[collection]/[id]/permanent.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]/duplicate",
		entrypoint: resolveRoute("api/content/[collection]/[id]/duplicate.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]/publish",
		entrypoint: resolveRoute("api/content/[collection]/[id]/publish.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]/unpublish",
		entrypoint: resolveRoute("api/content/[collection]/[id]/unpublish.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]/discard-draft",
		entrypoint: resolveRoute("api/content/[collection]/[id]/discard-draft.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]/compare",
		entrypoint: resolveRoute("api/content/[collection]/[id]/compare.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]/translations",
		entrypoint: resolveRoute("api/content/[collection]/[id]/translations.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]/schedule",
		entrypoint: resolveRoute("api/content/[collection]/[id]/schedule.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/revisions/[revisionId]",
		entrypoint: resolveRoute("api/revisions/[revisionId]/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/revisions/[revisionId]/restore",
		entrypoint: resolveRoute("api/revisions/[revisionId]/restore.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/media",
		entrypoint: resolveRoute("api/media.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/media/upload-url",
		entrypoint: resolveRoute("api/media/upload-url.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/media/file/[key]",
		entrypoint: resolveRoute("api/media/file/[key].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/media/[id]",
		entrypoint: resolveRoute("api/media/[id].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/media/[id]/confirm",
		entrypoint: resolveRoute("api/media/[id]/confirm.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/media/providers",
		entrypoint: resolveRoute("api/media/providers/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/media/providers/[providerId]",
		entrypoint: resolveRoute("api/media/providers/[providerId]/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/media/providers/[providerId]/[itemId]",
		entrypoint: resolveRoute("api/media/providers/[providerId]/[itemId].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/import/probe",
		entrypoint: resolveRoute("api/import/probe.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/import/wordpress/analyze",
		entrypoint: resolveRoute("api/import/wordpress/analyze.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/import/wordpress/prepare",
		entrypoint: resolveRoute("api/import/wordpress/prepare.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/import/wordpress/execute",
		entrypoint: resolveRoute("api/import/wordpress/execute.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/import/wordpress/media",
		entrypoint: resolveRoute("api/import/wordpress/media.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/import/wordpress/rewrite-urls",
		entrypoint: resolveRoute("api/import/wordpress/rewrite-urls.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/import/wordpress-plugin/analyze",
		entrypoint: resolveRoute("api/import/wordpress-plugin/analyze.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/import/wordpress-plugin/execute",
		entrypoint: resolveRoute("api/import/wordpress-plugin/execute.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/import/wordpress-plugin/callback",
		entrypoint: resolveRoute("api/import/wordpress-plugin/callback.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/schema",
		entrypoint: resolveRoute("api/schema/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/typegen",
		entrypoint: resolveRoute("api/typegen.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/schema/collections",
		entrypoint: resolveRoute("api/schema/collections/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/schema/collections/[slug]",
		entrypoint: resolveRoute("api/schema/collections/[slug]/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/schema/collections/[slug]/fields",
		entrypoint: resolveRoute("api/schema/collections/[slug]/fields/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/schema/collections/[slug]/fields/reorder",
		entrypoint: resolveRoute("api/schema/collections/[slug]/fields/reorder.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/schema/collections/[slug]/fields/[fieldSlug]",
		entrypoint: resolveRoute("api/schema/collections/[slug]/fields/[fieldSlug].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/schema/orphans",
		entrypoint: resolveRoute("api/schema/orphans/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/schema/orphans/[slug]",
		entrypoint: resolveRoute("api/schema/orphans/[slug].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/settings",
		entrypoint: resolveRoute("api/settings.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/snapshot",
		entrypoint: resolveRoute("api/snapshot.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/taxonomies",
		entrypoint: resolveRoute("api/taxonomies/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/taxonomies/[name]/terms",
		entrypoint: resolveRoute("api/taxonomies/[name]/terms/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/taxonomies/[name]/terms/[slug]",
		entrypoint: resolveRoute("api/taxonomies/[name]/terms/[slug].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/content/[collection]/[id]/terms/[taxonomy]",
		entrypoint: resolveRoute("api/content/[collection]/[id]/terms/[taxonomy].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/plugins",
		entrypoint: resolveRoute("api/admin/plugins/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/plugins/[id]",
		entrypoint: resolveRoute("api/admin/plugins/[id]/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/plugins/[id]/enable",
		entrypoint: resolveRoute("api/admin/plugins/[id]/enable.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/plugins/[id]/disable",
		entrypoint: resolveRoute("api/admin/plugins/[id]/disable.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/plugins/marketplace",
		entrypoint: resolveRoute("api/admin/plugins/marketplace/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/plugins/marketplace/[id]",
		entrypoint: resolveRoute("api/admin/plugins/marketplace/[id]/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/plugins/marketplace/[id]/icon",
		entrypoint: resolveRoute("api/admin/plugins/marketplace/[id]/icon.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/plugins/marketplace/[id]/install",
		entrypoint: resolveRoute("api/admin/plugins/marketplace/[id]/install.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/plugins/[id]/update",
		entrypoint: resolveRoute("api/admin/plugins/[id]/update.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/plugins/[id]/uninstall",
		entrypoint: resolveRoute("api/admin/plugins/[id]/uninstall.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/plugins/updates",
		entrypoint: resolveRoute("api/admin/plugins/updates.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/hooks/exclusive",
		entrypoint: resolveRoute("api/admin/hooks/exclusive/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/hooks/exclusive/[hookName]",
		entrypoint: resolveRoute("api/admin/hooks/exclusive/[hookName].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/themes/marketplace",
		entrypoint: resolveRoute("api/admin/themes/marketplace/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/themes/marketplace/[id]",
		entrypoint: resolveRoute("api/admin/themes/marketplace/[id]/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/themes/marketplace/[id]/thumbnail",
		entrypoint: resolveRoute("api/admin/themes/marketplace/[id]/thumbnail.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/themes/preview",
		entrypoint: resolveRoute("api/themes/preview.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/users",
		entrypoint: resolveRoute("api/admin/users/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/bylines",
		entrypoint: resolveRoute("api/admin/bylines/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/bylines/[id]",
		entrypoint: resolveRoute("api/admin/bylines/[id]/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/users/[id]",
		entrypoint: resolveRoute("api/admin/users/[id]/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/users/[id]/disable",
		entrypoint: resolveRoute("api/admin/users/[id]/disable.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/users/[id]/enable",
		entrypoint: resolveRoute("api/admin/users/[id]/enable.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/users/[id]/send-recovery",
		entrypoint: resolveRoute("api/admin/users/[id]/send-recovery.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/api-tokens",
		entrypoint: resolveRoute("api/admin/api-tokens/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/api-tokens/[id]",
		entrypoint: resolveRoute("api/admin/api-tokens/[id].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/oauth-clients",
		entrypoint: resolveRoute("api/admin/oauth-clients/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/oauth-clients/[id]",
		entrypoint: resolveRoute("api/admin/oauth-clients/[id].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/oauth/device/code",
		entrypoint: resolveRoute("api/oauth/device/code.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/oauth/device/token",
		entrypoint: resolveRoute("api/oauth/device/token.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/oauth/device/authorize",
		entrypoint: resolveRoute("api/oauth/device/authorize.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/oauth/token/refresh",
		entrypoint: resolveRoute("api/oauth/token/refresh.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/oauth/token/revoke",
		entrypoint: resolveRoute("api/oauth/token/revoke.ts")
	});
	injectRoute({
		pattern: "/_emdash/.well-known/auth",
		entrypoint: resolveRoute("api/well-known/auth.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/oauth/token",
		entrypoint: resolveRoute("api/oauth/token.ts")
	});
	injectRoute({
		pattern: "/_emdash/oauth/authorize",
		entrypoint: resolveRoute("api/oauth/authorize.ts")
	});
	injectRoute({
		pattern: "/.well-known/oauth-protected-resource",
		entrypoint: resolveRoute("api/well-known/oauth-protected-resource.ts")
	});
	injectRoute({
		pattern: "/_emdash/.well-known/oauth-authorization-server",
		entrypoint: resolveRoute("api/well-known/oauth-authorization-server.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/plugins/[pluginId]/[...path]",
		entrypoint: resolveRoute("api/plugins/[pluginId]/[...path].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/menus",
		entrypoint: resolveRoute("api/menus/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/menus/[name]",
		entrypoint: resolveRoute("api/menus/[name].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/menus/[name]/items",
		entrypoint: resolveRoute("api/menus/[name]/items.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/menus/[name]/reorder",
		entrypoint: resolveRoute("api/menus/[name]/reorder.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/widget-areas",
		entrypoint: resolveRoute("api/widget-areas/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/widget-components",
		entrypoint: resolveRoute("api/widget-components.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/widget-areas/[name]",
		entrypoint: resolveRoute("api/widget-areas/[name].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/widget-areas/[name]/widgets",
		entrypoint: resolveRoute("api/widget-areas/[name]/widgets.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/widget-areas/[name]/widgets/[id]",
		entrypoint: resolveRoute("api/widget-areas/[name]/widgets/[id].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/widget-areas/[name]/reorder",
		entrypoint: resolveRoute("api/widget-areas/[name]/reorder.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/sections",
		entrypoint: resolveRoute("api/sections/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/sections/[slug]",
		entrypoint: resolveRoute("api/sections/[slug].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/redirects",
		entrypoint: resolveRoute("api/redirects/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/redirects/404s/summary",
		entrypoint: resolveRoute("api/redirects/404s/summary.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/redirects/404s",
		entrypoint: resolveRoute("api/redirects/404s/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/redirects/[id]",
		entrypoint: resolveRoute("api/redirects/[id].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/search",
		entrypoint: resolveRoute("api/search/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/search/suggest",
		entrypoint: resolveRoute("api/search/suggest.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/search/stats",
		entrypoint: resolveRoute("api/search/stats.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/search/rebuild",
		entrypoint: resolveRoute("api/search/rebuild.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/search/enable",
		entrypoint: resolveRoute("api/search/enable.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/comments/[collection]/[contentId]",
		entrypoint: resolveRoute("api/comments/[collection]/[contentId]/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/comments",
		entrypoint: resolveRoute("api/admin/comments/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/comments/counts",
		entrypoint: resolveRoute("api/admin/comments/counts.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/comments/bulk",
		entrypoint: resolveRoute("api/admin/comments/bulk.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/comments/[id]/status",
		entrypoint: resolveRoute("api/admin/comments/[id]/status.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/comments/[id]",
		entrypoint: resolveRoute("api/admin/comments/[id].ts")
	});
	injectRoute({
		pattern: "/sitemap.xml",
		entrypoint: resolveRoute("sitemap.xml.ts")
	});
	injectRoute({
		pattern: "/robots.txt",
		entrypoint: resolveRoute("robots.txt.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/setup/status",
		entrypoint: resolveRoute("api/setup/status.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/setup",
		entrypoint: resolveRoute("api/setup/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/setup/admin",
		entrypoint: resolveRoute("api/setup/admin.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/setup/admin/verify",
		entrypoint: resolveRoute("api/setup/admin-verify.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/setup/dev-bypass",
		entrypoint: resolveRoute("api/setup/dev-bypass.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/setup/dev-reset",
		entrypoint: resolveRoute("api/setup/dev-reset.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/me",
		entrypoint: resolveRoute("api/auth/me.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/logout",
		entrypoint: resolveRoute("api/auth/logout.ts")
	});
}
/**
* Injects the MCP (Model Context Protocol) server route.
* Only injected when `mcp: true` is set in the EmDash config.
*/
function injectMcpRoute(injectRoute) {
	injectRoute({
		pattern: "/_emdash/api/mcp",
		entrypoint: resolveRoute("api/mcp.ts")
	});
}
/**
* Injects passkey/oauth/magic-link auth routes.
* Only used when NOT using external auth.
*/
function injectBuiltinAuthRoutes(injectRoute) {
	injectRoute({
		pattern: "/_emdash/api/auth/passkey/options",
		entrypoint: resolveRoute("api/auth/passkey/options.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/passkey/verify",
		entrypoint: resolveRoute("api/auth/passkey/verify.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/passkey",
		entrypoint: resolveRoute("api/auth/passkey/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/passkey/register/options",
		entrypoint: resolveRoute("api/auth/passkey/register/options.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/passkey/register/verify",
		entrypoint: resolveRoute("api/auth/passkey/register/verify.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/passkey/[id]",
		entrypoint: resolveRoute("api/auth/passkey/[id].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/dev-bypass",
		entrypoint: resolveRoute("api/auth/dev-bypass.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/invite",
		entrypoint: resolveRoute("api/auth/invite/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/invite/accept",
		entrypoint: resolveRoute("api/auth/invite/accept.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/invite/complete",
		entrypoint: resolveRoute("api/auth/invite/complete.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/magic-link/send",
		entrypoint: resolveRoute("api/auth/magic-link/send.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/magic-link/verify",
		entrypoint: resolveRoute("api/auth/magic-link/verify.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/oauth/[provider]",
		entrypoint: resolveRoute("api/auth/oauth/[provider].ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/oauth/[provider]/callback",
		entrypoint: resolveRoute("api/auth/oauth/[provider]/callback.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/signup/request",
		entrypoint: resolveRoute("api/auth/signup/request.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/signup/verify",
		entrypoint: resolveRoute("api/auth/signup/verify.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/auth/signup/complete",
		entrypoint: resolveRoute("api/auth/signup/complete.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/allowed-domains",
		entrypoint: resolveRoute("api/admin/allowed-domains/index.ts")
	});
	injectRoute({
		pattern: "/_emdash/api/admin/allowed-domains/[domain]",
		entrypoint: resolveRoute("api/admin/allowed-domains/[domain].ts")
	});
}

//#endregion
//#region src/astro/integration/virtual-modules.ts
/**
* Virtual Module Generators
*
* Functions that generate virtual module content for Vite.
* These modules statically import configured dependencies
* so Vite can properly resolve and bundle them.
*/
const TS_SOURCE_EXT_RE = /^\.(ts|tsx|mts|cts|jsx)$/;
/** Pattern to remove scoped package prefix from plugin ID */
const SCOPED_PREFIX_PATTERN = /^@[^/]+\/plugin-/;
/** Pattern to remove emdash-plugin- prefix from plugin ID */
const EMDASH_PREFIX_PATTERN = /^emdash-plugin-/;
const VIRTUAL_CONFIG_ID = "virtual:emdash/config";
const RESOLVED_VIRTUAL_CONFIG_ID = "\0" + VIRTUAL_CONFIG_ID;
const VIRTUAL_DIALECT_ID = "virtual:emdash/dialect";
const RESOLVED_VIRTUAL_DIALECT_ID = "\0" + VIRTUAL_DIALECT_ID;
const VIRTUAL_STORAGE_ID = "virtual:emdash/storage";
const RESOLVED_VIRTUAL_STORAGE_ID = "\0" + VIRTUAL_STORAGE_ID;
const VIRTUAL_ADMIN_REGISTRY_ID = "virtual:emdash/admin-registry";
const RESOLVED_VIRTUAL_ADMIN_REGISTRY_ID = "\0" + VIRTUAL_ADMIN_REGISTRY_ID;
const VIRTUAL_PLUGINS_ID = "virtual:emdash/plugins";
const RESOLVED_VIRTUAL_PLUGINS_ID = "\0" + VIRTUAL_PLUGINS_ID;
const VIRTUAL_SANDBOX_RUNNER_ID = "virtual:emdash/sandbox-runner";
const RESOLVED_VIRTUAL_SANDBOX_RUNNER_ID = "\0" + VIRTUAL_SANDBOX_RUNNER_ID;
const VIRTUAL_SANDBOXED_PLUGINS_ID = "virtual:emdash/sandboxed-plugins";
const RESOLVED_VIRTUAL_SANDBOXED_PLUGINS_ID = "\0" + VIRTUAL_SANDBOXED_PLUGINS_ID;
const VIRTUAL_AUTH_ID = "virtual:emdash/auth";
const RESOLVED_VIRTUAL_AUTH_ID = "\0" + VIRTUAL_AUTH_ID;
const VIRTUAL_MEDIA_PROVIDERS_ID = "virtual:emdash/media-providers";
const RESOLVED_VIRTUAL_MEDIA_PROVIDERS_ID = "\0" + VIRTUAL_MEDIA_PROVIDERS_ID;
const VIRTUAL_BLOCK_COMPONENTS_ID = "virtual:emdash/block-components";
const RESOLVED_VIRTUAL_BLOCK_COMPONENTS_ID = "\0" + VIRTUAL_BLOCK_COMPONENTS_ID;
const VIRTUAL_SEED_ID = "virtual:emdash/seed";
const RESOLVED_VIRTUAL_SEED_ID = "\0" + VIRTUAL_SEED_ID;
/**
* Generates the config virtual module.
*/
function generateConfigModule(serializableConfig) {
	return `export default ${JSON.stringify(serializableConfig)};`;
}
/**
* Generates the dialect virtual module.
* Statically imports the configured database dialect and exports the dialect type.
*
* For D1 adapters, also re-exports session helpers (isSessionEnabled, getD1Binding,
* getDefaultConstraint, getBookmarkCookieName, createSessionDialect) used by
* middleware for per-request read replica sessions.
*
* For non-D1 adapters, session exports are no-ops.
*/
function generateDialectModule(dbEntrypoint, dbType, dbConfig) {
	if (!dbEntrypoint) return [
		`export const createDialect = undefined;`,
		`export const dialectType = "sqlite";`,
		`export const isSessionEnabled = () => false;`,
		`export const getD1Binding = () => null;`,
		`export const getDefaultConstraint = () => "first-unconstrained";`,
		`export const getBookmarkCookieName = () => "";`,
		`export const createSessionDialect = undefined;`
	].join("\n");
	const type = dbType ?? "sqlite";
	const isD1 = dbEntrypoint.includes("cloudflare") && dbEntrypoint.includes("d1");
	const sessionMode = isD1 && dbConfig && typeof dbConfig === "object" && "session" in dbConfig ? dbConfig.session : void 0;
	if (isD1 && !!sessionMode && sessionMode !== "disabled") return `
import { createDialect as _createDialect } from "${dbEntrypoint}";
export { isSessionEnabled, getD1Binding, getDefaultConstraint, getBookmarkCookieName, createSessionDialect } from "${dbEntrypoint}";
export const createDialect = _createDialect;
export const dialectType = ${JSON.stringify(type)};
`;
	return `
import { createDialect as _createDialect } from "${dbEntrypoint}";
export const createDialect = _createDialect;
export const dialectType = ${JSON.stringify(type)};
export const isSessionEnabled = () => false;
export const getD1Binding = () => null;
export const getDefaultConstraint = () => "first-unconstrained";
export const getBookmarkCookieName = () => "";
export const createSessionDialect = undefined;
`;
}
/**
* Generates the storage virtual module.
* Statically imports the configured storage adapter.
*/
function generateStorageModule(storageEntrypoint) {
	if (!storageEntrypoint) return `export const createStorage = undefined;`;
	return `
import { createStorage as _createStorage } from "${storageEntrypoint}";
export const createStorage = _createStorage;
`;
}
/**
* Generates the auth virtual module.
* Statically imports the configured auth provider.
*/
function generateAuthModule(authEntrypoint) {
	if (!authEntrypoint) return `export const authenticate = undefined;`;
	return `
import { authenticate as _authenticate } from "${authEntrypoint}";
export const authenticate = _authenticate;
`;
}
/**
* Generates the plugins module.
* Imports and instantiates all plugins at runtime.
*
* Handles two plugin formats:
* - **Native**: imports `createPlugin` and calls it with options
* - **Standard**: imports the default export and wraps it with `adaptSandboxEntry`
*
* The format is determined by `descriptor.format`:
* - `"standard"` -- uses adaptSandboxEntry
* - `"native"` or undefined -- uses createPlugin
*
* This is critical for Cloudflare Workers where globals don't persist
* between build time and runtime.
*/
function generatePluginsModule(descriptors) {
	if (descriptors.length === 0) return `export const plugins = [];`;
	const imports = [];
	const instantiations = [];
	let needsAdapter = false;
	descriptors.forEach((descriptor, index) => {
		if (descriptor.format === "standard") {
			needsAdapter = true;
			const varName = `pluginDef${index}`;
			imports.push(`import ${varName} from "${descriptor.entrypoint}";`);
			instantiations.push(`adaptSandboxEntry(${varName}, ${JSON.stringify({
				id: descriptor.id,
				version: descriptor.version,
				capabilities: descriptor.capabilities,
				allowedHosts: descriptor.allowedHosts,
				storage: descriptor.storage,
				adminPages: descriptor.adminPages,
				adminWidgets: descriptor.adminWidgets
			})})`);
		} else {
			const varName = `createPlugin${index}`;
			imports.push(`import { createPlugin as ${varName} } from "${descriptor.entrypoint}";`);
			instantiations.push(`${varName}(${JSON.stringify(descriptor.options ?? {})})`);
		}
	});
	return `
// Auto-generated plugins module
// Imports and instantiates all configured plugins at runtime

${needsAdapter ? `import { adaptSandboxEntry } from "emdash/plugins/adapt-sandbox-entry";\n` : ""}${imports.join("\n")}

/** Resolved plugins array */
export const plugins = [
  ${instantiations.join(",\n  ")}
];
`;
}
/**
* Generates the admin registry module.
* Uses adminEntry from plugin descriptors to statically import admin modules.
*/
function generateAdminRegistryModule(descriptors) {
	const adminDescriptors = descriptors.filter((d) => d.adminEntry);
	if (adminDescriptors.length === 0) return `export const pluginAdmins = {};`;
	const imports = [];
	const entries = [];
	adminDescriptors.forEach((descriptor, index) => {
		const varName = `admin${index}`;
		const pluginId = descriptor.id ?? descriptor.entrypoint.replace(SCOPED_PREFIX_PATTERN, "").replace(EMDASH_PREFIX_PATTERN, "");
		imports.push(`import * as ${varName} from "${descriptor.adminEntry}";`);
		entries.push(`  "${pluginId}": ${varName},`);
	});
	return `
// Auto-generated plugin admin registry
${imports.join("\n")}

export const pluginAdmins = {
${entries.join("\n")}
};
`;
}
/**
* Generates the sandbox runner module.
* Imports the configured sandbox runner factory or provides a noop default.
*/
function generateSandboxRunnerModule(sandboxRunner) {
	if (!sandboxRunner) return `
// No sandbox runner configured - sandboxed plugins disabled
import { createNoopSandboxRunner } from "emdash";

export const createSandboxRunner = createNoopSandboxRunner;
export const sandboxEnabled = false;
`;
	return `
// Auto-generated sandbox runner module
import { createSandboxRunner as _createSandboxRunner } from "${sandboxRunner}";

export const createSandboxRunner = _createSandboxRunner;
export const sandboxEnabled = true;
`;
}
/**
* Generates the media providers module.
* Imports and instantiates configured media providers at runtime.
*/
function generateMediaProvidersModule(descriptors) {
	const localDisabled = descriptors.some((d) => d.id === "local" && d.config.enabled === false);
	const imports = [];
	const entries = [];
	if (!localDisabled) {
		imports.push(`import { createMediaProvider as createLocalProvider } from "emdash/media/local-runtime";`);
		entries.push(`{
	id: "local",
	name: "Library",
	icon: "folder",
	capabilities: { browse: true, search: false, upload: true, delete: true },
	createProvider: (ctx) => createLocalProvider({ ...ctx, enabled: true }),
}`);
	}
	descriptors.filter((d) => d.id !== "local" || d.config.enabled !== false).filter((d) => d.id !== "local").forEach((descriptor, index) => {
		const varName = `createProvider${index}`;
		imports.push(`import { createMediaProvider as ${varName} } from "${descriptor.entrypoint}";`);
		entries.push(`{
	id: ${JSON.stringify(descriptor.id)},
	name: ${JSON.stringify(descriptor.name)},
	icon: ${JSON.stringify(descriptor.icon)},
	capabilities: ${JSON.stringify(descriptor.capabilities)},
	createProvider: (ctx) => ${varName}({ ...${JSON.stringify(descriptor.config)}, ...ctx }),
}`);
	});
	return `
// Auto-generated media providers module
${imports.join("\n")}

/** Media provider descriptors with factory functions */
export const mediaProviders = [
  ${entries.join(",\n  ")}
];
`;
}
/**
* Generates the block components module.
* Collects and merges `blockComponents` exports from plugin component entries.
*/
function generateBlockComponentsModule(descriptors) {
	const withComponents = descriptors.filter((d) => d.componentsEntry);
	if (withComponents.length === 0) return `export const pluginBlockComponents = {};`;
	const imports = [];
	const spreads = [];
	withComponents.forEach((d, i) => {
		imports.push(`import { blockComponents as bc${i} } from "${d.componentsEntry}";`);
		spreads.push(`...bc${i}`);
	});
	return `${imports.join("\n")}\nexport const pluginBlockComponents = { ${spreads.join(", ")} };`;
}
/**
* Generates the seed virtual module.
* Reads the user's seed file at build time (in Node context) and embeds it,
* so the runtime doesn't need filesystem access (required for workerd).
*
* Exports `userSeed` (user's seed or null) and `seed` (user's seed or default).
*/
function generateSeedModule(projectRoot) {
	let userSeedJson = null;
	try {
		const content = readFileSync(resolve(projectRoot, ".emdash", "seed.json"), "utf-8");
		JSON.parse(content);
		userSeedJson = content;
	} catch {}
	if (!userSeedJson) try {
		const pkgContent = readFileSync(resolve(projectRoot, "package.json"), "utf-8");
		const pkg = JSON.parse(pkgContent);
		if (pkg.emdash?.seed) {
			const content = readFileSync(resolve(projectRoot, pkg.emdash.seed), "utf-8");
			JSON.parse(content);
			userSeedJson = content;
		}
	} catch {}
	if (userSeedJson) return [`export const userSeed = ${userSeedJson};`, `export const seed = userSeed;`].join("\n");
	return [`export const userSeed = null;`, `export const seed = ${JSON.stringify(defaultSeed)};`].join("\n");
}
/**
* Resolve a module specifier from the project's context.
* Uses Node.js require.resolve with the project root as base.
*/
function resolveModulePathFromProject(specifier, projectRoot) {
	return createRequire(resolve(projectRoot, "package.json")).resolve(specifier);
}
/**
* Generates the sandboxed plugins module.
* Resolves plugin entrypoints to files, reads them, and embeds the code.
*
* At runtime, middleware uses SandboxRunner to load these into isolates.
*/
function generateSandboxedPluginsModule(sandboxed, projectRoot) {
	if (sandboxed.length === 0) return `
// No sandboxed plugins configured
export const sandboxedPlugins = [];
`;
	const pluginEntries = [];
	for (const descriptor of sandboxed) {
		const bundleSpecifier = descriptor.entrypoint;
		const filePath = resolveModulePathFromProject(bundleSpecifier, projectRoot);
		const ext = filePath.slice(filePath.lastIndexOf("."));
		if (TS_SOURCE_EXT_RE.test(ext)) throw new Error(`Sandboxed plugin "${descriptor.id}" entrypoint "${bundleSpecifier}" resolves to unbuilt source (${filePath}). Sandbox entries must be pre-built JavaScript. Ensure the plugin's package.json exports point to built files (e.g. dist/*.mjs) and run the plugin's build step before building the site.`);
		const code = readFileSync(filePath, "utf-8");
		pluginEntries.push(`{
    id: ${JSON.stringify(descriptor.id)},
    version: ${JSON.stringify(descriptor.version)},
    options: ${JSON.stringify(descriptor.options ?? {})},
    capabilities: ${JSON.stringify(descriptor.capabilities ?? [])},
    allowedHosts: ${JSON.stringify(descriptor.allowedHosts ?? [])},
    storage: ${JSON.stringify(descriptor.storage ?? {})},
    adminPages: ${JSON.stringify(descriptor.adminPages ?? [])},
    adminWidgets: ${JSON.stringify(descriptor.adminWidgets ?? [])},
    adminEntry: ${JSON.stringify(descriptor.adminEntry)},
    // Code read from: ${filePath}
    code: ${JSON.stringify(code)},
  }`);
	}
	return `
// Auto-generated sandboxed plugins module
// Plugin code is embedded at build time

/**
 * Sandboxed plugin entries with embedded code.
 * Loaded at runtime via SandboxRunner.
 */
export const sandboxedPlugins = [
  ${pluginEntries.join(",\n  ")}
];
`;
}

//#endregion
//#region src/astro/integration/vite-config.ts
/**
* Vite Plugin Configuration
*
* Defines the Vite plugin that handles virtual modules and other
* Vite-specific configuration for EmDash.
*/
/**
* Resolve path to the admin package dist directory.
* Used for Vite alias to ensure the package is found in pnpm's isolated node_modules.
*/
function resolveAdminDist() {
	return dirname(createRequire(import.meta.url).resolve("@emdash-cms/admin"));
}
/**
* Resolve path to the admin package source directory.
* In dev mode, we alias @emdash-cms/admin to the source so Vite processes it
* directly — giving instant HMR instead of requiring a rebuild + restart.
*/
function resolveAdminSource() {
	const require = createRequire(import.meta.url);
	const packageRoot = resolve(dirname(require.resolve("@emdash-cms/admin")), "..");
	const srcEntry = resolve(packageRoot, "src", "index.ts");
	try {
		if (require("node:fs").existsSync(srcEntry)) return resolve(packageRoot, "src");
	} catch {}
}
/**
* Creates the EmDash virtual modules Vite plugin.
*/
function createVirtualModulesPlugin(options) {
	const { serializableConfig, resolvedConfig, pluginDescriptors, astroConfig } = options;
	return {
		name: "emdash-virtual-modules",
		resolveId(id) {
			if (id === VIRTUAL_CONFIG_ID) return RESOLVED_VIRTUAL_CONFIG_ID;
			if (id === VIRTUAL_DIALECT_ID) return RESOLVED_VIRTUAL_DIALECT_ID;
			if (id === VIRTUAL_STORAGE_ID) return RESOLVED_VIRTUAL_STORAGE_ID;
			if (id === VIRTUAL_ADMIN_REGISTRY_ID) return RESOLVED_VIRTUAL_ADMIN_REGISTRY_ID;
			if (id === VIRTUAL_PLUGINS_ID) return RESOLVED_VIRTUAL_PLUGINS_ID;
			if (id === VIRTUAL_SANDBOX_RUNNER_ID) return RESOLVED_VIRTUAL_SANDBOX_RUNNER_ID;
			if (id === VIRTUAL_SANDBOXED_PLUGINS_ID) return RESOLVED_VIRTUAL_SANDBOXED_PLUGINS_ID;
			if (id === VIRTUAL_AUTH_ID) return RESOLVED_VIRTUAL_AUTH_ID;
			if (id === VIRTUAL_MEDIA_PROVIDERS_ID) return RESOLVED_VIRTUAL_MEDIA_PROVIDERS_ID;
			if (id === VIRTUAL_BLOCK_COMPONENTS_ID) return RESOLVED_VIRTUAL_BLOCK_COMPONENTS_ID;
			if (id === VIRTUAL_SEED_ID) return RESOLVED_VIRTUAL_SEED_ID;
		},
		load(id) {
			if (id === RESOLVED_VIRTUAL_CONFIG_ID) return generateConfigModule(serializableConfig);
			if (id === RESOLVED_VIRTUAL_DIALECT_ID) return generateDialectModule(resolvedConfig.database?.entrypoint, resolvedConfig.database?.type, resolvedConfig.database?.config);
			if (id === RESOLVED_VIRTUAL_STORAGE_ID) return generateStorageModule(resolvedConfig.storage?.entrypoint);
			if (id === RESOLVED_VIRTUAL_PLUGINS_ID) return generatePluginsModule(pluginDescriptors);
			if (id === RESOLVED_VIRTUAL_ADMIN_REGISTRY_ID) return generateAdminRegistryModule([...pluginDescriptors, ...resolvedConfig.sandboxed ?? []]);
			if (id === RESOLVED_VIRTUAL_SANDBOX_RUNNER_ID) return generateSandboxRunnerModule(resolvedConfig.sandboxRunner);
			if (id === RESOLVED_VIRTUAL_SANDBOXED_PLUGINS_ID) {
				const projectRoot = fileURLToPath(astroConfig.root);
				return generateSandboxedPluginsModule(resolvedConfig.sandboxed ?? [], projectRoot);
			}
			if (id === RESOLVED_VIRTUAL_AUTH_ID) {
				const authDescriptor = resolvedConfig.auth;
				if (!authDescriptor || !("entrypoint" in authDescriptor)) return generateAuthModule(void 0);
				return generateAuthModule(authDescriptor.entrypoint);
			}
			if (id === RESOLVED_VIRTUAL_MEDIA_PROVIDERS_ID) return generateMediaProvidersModule(resolvedConfig.mediaProviders ?? []);
			if (id === RESOLVED_VIRTUAL_BLOCK_COMPONENTS_ID) return generateBlockComponentsModule(pluginDescriptors);
			if (id === RESOLVED_VIRTUAL_SEED_ID) return generateSeedModule(fileURLToPath(astroConfig.root));
		}
	};
}
/**
* Modules that contain native Node.js addons or Node-only code.
* These must be external in SSR to avoid bundling failures on Node.
* On Cloudflare, the adapter handles its own externalization — setting
* ssr.external there conflicts with @cloudflare/vite-plugin's validation.
*/
const NODE_NATIVE_EXTERNALS = [
	"better-sqlite3",
	"bindings",
	"file-uri-to-path",
	"@libsql/kysely-libsql",
	"pg"
];
/**
* Detect whether the Cloudflare adapter is being used.
*/
function isCloudflareAdapter(astroConfig) {
	return astroConfig.adapter?.name === "@astrojs/cloudflare";
}
/**
* Creates the Vite config update for EmDash.
*/
function createViteConfig(options, command) {
	const adminDistPath = resolveAdminDist();
	const cloudflare = isCloudflareAdapter(options.astroConfig);
	const adminSourcePath = command === "dev" ? resolveAdminSource() : void 0;
	const useSource = adminSourcePath !== void 0;
	return {
		resolve: {
			dedupe: [
				"@emdash-cms/admin",
				"react",
				"react-dom"
			],
			alias: [{
				find: "@emdash-cms/admin/styles.css",
				replacement: resolve(adminDistPath, "styles.css")
			}, {
				find: "@emdash-cms/admin",
				replacement: useSource ? adminSourcePath : adminDistPath
			}]
		},
		plugins: [createVirtualModulesPlugin(options)],
		ssr: cloudflare ? {
			noExternal: ["emdash", "@emdash-cms/admin"],
			optimizeDeps: {
				exclude: ["virtual:emdash"],
				include: [
					"emdash > @portabletext/toolkit",
					"emdash > @unpic/placeholder",
					"emdash > blurhash",
					"emdash > croner",
					"emdash > image-size",
					"emdash > jose",
					"emdash > jpeg-js",
					"emdash > kysely",
					"emdash > mime/lite",
					"emdash > modern-tar",
					"emdash > sanitize-html",
					"emdash > ulidx",
					"emdash > upng-js",
					"emdash > astro-portabletext",
					"emdash > sax",
					"emdash > sanitize-html > parse5",
					"emdash > @emdash-cms/gutenberg-to-portable-text > @wordpress/block-serialization-default-parser",
					"emdash > @emdash-cms/auth > @oslojs/crypto/ecdsa",
					"emdash > @emdash-cms/auth > @oslojs/crypto/sha2",
					"emdash > @emdash-cms/auth > @oslojs/webauthn",
					"react",
					"react/jsx-dev-runtime",
					"react/jsx-runtime",
					"react-dom",
					"react-dom/server",
					"astro > zod/v4",
					"astro > zod/v4/core",
					"@emdash-cms/cloudflare > kysely-d1",
					"astro/virtual-modules/middleware.js",
					"astro/virtual-modules/live-config",
					"astro/content/runtime",
					"astro/assets/utils/inferRemoteSize.js",
					"astro/assets/fonts/runtime.js",
					"@astrojs/cloudflare/image-service"
				]
			}
		} : {
			external: NODE_NATIVE_EXTERNALS,
			noExternal: ["emdash", "@emdash-cms/admin"]
		},
		optimizeDeps: {
			include: useSource ? ["@astrojs/react/client.js"] : ["@emdash-cms/admin", "@astrojs/react/client.js"],
			exclude: cloudflare ? ["virtual:emdash"] : [...NODE_NATIVE_EXTERNALS, "virtual:emdash"]
		}
	};
}

//#endregion
//#region src/astro/integration/runtime.ts
/**
* Get stored config from global
* This is set by the virtual module at build time
*/
function getStoredConfig() {
	return globalThis.__emdashConfig || null;
}

//#endregion
//#region src/astro/integration/index.ts
/** Default storage: Local filesystem in .emdash directory */
const DEFAULT_STORAGE = local({
	directory: "./.emdash/uploads",
	baseUrl: "/_emdash/api/media/file"
});
const dim = (s) => `\x1b[2m${s}\x1b[22m`;
const bold = (s) => `\x1b[1m${s}\x1b[22m`;
const cyan = (s) => `\x1b[36m${s}\x1b[39m`;
/** Print the EmDash startup banner */
function printBanner(_logger) {
	const banner = `

  ${bold(cyan("— E M D A S H —"))}
   `;
	console.log(banner);
}
/** Print route injection summary */
function printRoutesSummary(_logger) {
	console.log(`\n  ${dim("›")} Admin UI    ${cyan("/_emdash/admin")}`);
	console.log(`  ${dim("›")} API         ${cyan("/_emdash/api/*")}`);
	console.log("");
}
/**
* Create the EmDash Astro integration
*/
function emdash(config = {}) {
	const resolvedConfig = {
		...config,
		storage: config.storage ?? DEFAULT_STORAGE
	};
	if (resolvedConfig.marketplace) {
		const url = resolvedConfig.marketplace;
		try {
			const parsed = new URL(url);
			const isLocalhost = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
			if (parsed.protocol !== "https:" && !isLocalhost) throw new Error(`Marketplace URL must use HTTPS (got ${parsed.protocol}). Only localhost URLs are allowed over HTTP.`);
		} catch (e) {
			if (e instanceof TypeError) throw new Error(`Invalid marketplace URL: "${url}"`, { cause: e });
			throw e;
		}
		if (!resolvedConfig.sandboxRunner) throw new Error("Marketplace requires `sandboxRunner` to be configured. Marketplace plugins run in sandboxed V8 isolates.");
	}
	if (resolvedConfig.passkeyPublicOrigin) {
		const raw = resolvedConfig.passkeyPublicOrigin;
		try {
			const parsed = new URL(raw);
			if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`passkeyPublicOrigin must be http or https (got ${parsed.protocol})`);
			resolvedConfig.passkeyPublicOrigin = parsed.origin;
		} catch (e) {
			if (e instanceof TypeError) throw new Error(`Invalid passkeyPublicOrigin: "${raw}"`, { cause: e });
			throw e;
		}
	}
	const pluginDescriptors = resolvedConfig.plugins ?? [];
	const sandboxedDescriptors = resolvedConfig.sandboxed ?? [];
	for (const descriptor of [...pluginDescriptors, ...sandboxedDescriptors]) if (descriptor.format === "standard") {
		if (descriptor.adminEntry) throw new Error(`Plugin "${descriptor.id}" is standard format but declares adminEntry. Standard plugins use Block Kit for admin UI, not React components. Remove adminEntry or change format to "native".`);
		if (descriptor.componentsEntry) throw new Error(`Plugin "${descriptor.id}" is standard format but declares componentsEntry. Portable Text block components require native format. Remove componentsEntry or change format to "native".`);
	}
	for (const descriptor of sandboxedDescriptors) if (descriptor.format !== "standard") throw new Error(`Plugin "${descriptor.id}" uses the native format and cannot be placed in \`sandboxed: []\`. Native plugins can only run in \`plugins: []\`. To sandbox this plugin, convert it to the standard format.`);
	const serializableConfig = {
		database: resolvedConfig.database,
		storage: resolvedConfig.storage,
		auth: resolvedConfig.auth,
		marketplace: resolvedConfig.marketplace,
		passkeyPublicOrigin: resolvedConfig.passkeyPublicOrigin
	};
	const useExternalAuth = !!(resolvedConfig.auth && "entrypoint" in resolvedConfig.auth);
	return {
		name: "emdash",
		hooks: {
			"astro:config:setup": ({ injectRoute, addMiddleware, logger, updateConfig, config: astroConfig, command }) => {
				printBanner(logger);
				if (astroConfig.i18n) {
					const routing = astroConfig.i18n.routing;
					serializableConfig.i18n = {
						defaultLocale: astroConfig.i18n.defaultLocale,
						locales: astroConfig.i18n.locales.map((l) => typeof l === "string" ? l : l.path),
						fallback: astroConfig.i18n.fallback,
						prefixDefaultLocale: typeof routing === "object" ? routing.prefixDefaultLocale ?? false : false
					};
				}
				updateConfig({ vite: createViteConfig({
					serializableConfig,
					resolvedConfig,
					pluginDescriptors,
					astroConfig
				}, command) });
				injectCoreRoutes(injectRoute);
				if (!useExternalAuth) injectBuiltinAuthRoutes(injectRoute);
				if (resolvedConfig.mcp) {
					injectMcpRoute(injectRoute);
					logger.info("MCP server enabled at /_emdash/api/mcp");
				}
				if (resolvedConfig.playground) addMiddleware({
					entrypoint: resolvedConfig.playground.middlewareEntrypoint,
					order: "pre"
				});
				addMiddleware({
					entrypoint: "emdash/middleware",
					order: "pre"
				});
				addMiddleware({
					entrypoint: "emdash/middleware/redirect",
					order: "pre"
				});
				if (!resolvedConfig.playground) {
					addMiddleware({
						entrypoint: "emdash/middleware/setup",
						order: "pre"
					});
					addMiddleware({
						entrypoint: "emdash/middleware/auth",
						order: "pre"
					});
				}
				addMiddleware({
					entrypoint: "emdash/middleware/request-context",
					order: "pre"
				});
				printRoutesSummary(logger);
			},
			"astro:server:setup": ({ server, logger }) => {
				server.httpServer?.once("listening", async () => {
					const { writeFile, readFile } = await import("node:fs/promises");
					const { resolve } = await import("node:path");
					const address = server.httpServer?.address();
					if (!address || typeof address === "string") return;
					const typegenUrl = `http://localhost:${address.port}/_emdash/api/typegen`;
					const outputPath = resolve(process.cwd(), "emdash-env.d.ts");
					try {
						const response = await fetch(typegenUrl, {
							method: "POST",
							headers: { "Content-Type": "application/json" }
						});
						if (!response.ok) {
							const body = await response.text().catch(() => "");
							logger.warn(`Typegen failed: ${response.status} ${body.slice(0, 200)}`);
							return;
						}
						const { data: result } = await response.json();
						let needsWrite = true;
						try {
							if (await readFile(outputPath, "utf-8") === result.types) needsWrite = false;
						} catch {}
						if (needsWrite) {
							await writeFile(outputPath, result.types, "utf-8");
							logger.info(`Generated emdash-env.d.ts (${result.collections} collections)`);
						}
					} catch (error) {
						const msg = error instanceof Error ? error.message : String(error);
						logger.warn(`Typegen failed: ${msg}`);
					}
				});
			},
			"astro:build:done": ({ logger }) => {
				logger.info("Build complete");
			}
		}
	};
}

//#endregion
export { emdash as default, getStoredConfig, local, s3 };
//# sourceMappingURL=index.mjs.map