import { n as __name } from "./chunk-BVHe6Par.js";
import { r as trimExtName } from "./getRelativePath-C4Au07ON.js";
import { t as defaultParser } from "./defaultParser-BD_N68Bo.js";
import { orderBy } from "natural-orderby";
import { createHash } from "node:crypto";
import path from "node:path";
import { uniqueBy } from "remeda";
import pLimit from "p-limit";
import { EventEmitter } from "node:events";

//#region src/context.ts
/**
* Context stack for tracking the current context values
*
* Note: This uses a global Map for simplicity in code generation scenarios.
* For concurrent runtime execution, consider using AsyncLocalStorage or
* instance-based context management.
*/
const contextStack = /* @__PURE__ */ new Map();
const contextDefaults = /* @__PURE__ */ new Map();
/**
* Provides a value to descendant components (Vue 3 style)
*
* @example
* ```ts
* const ThemeKey = Symbol('theme')
* provide(ThemeKey, { color: 'blue' })
* ```
*/
function provide(key, value) {
	if (!contextStack.has(key)) contextStack.set(key, []);
	contextStack.get(key).push(value);
}
/**
* Injects a value provided by an ancestor component (Vue 3 style)
*
* @example
* ```ts
* const theme = inject(ThemeKey, { color: 'default' })
* ```
*/
function inject(key, defaultValue) {
	const stack = contextStack.get(key);
	if (!stack || stack.length === 0) {
		if (defaultValue !== void 0) return defaultValue;
		const storedDefault = contextDefaults.get(key);
		if (storedDefault !== void 0) return storedDefault;
		throw new Error(`No value provided for key: ${key.toString()}`);
	}
	return stack[stack.length - 1];
}
/**
* Unprovides a value (for cleanup)
* @internal
*/
function unprovide(key) {
	const stack = contextStack.get(key);
	if (stack && stack.length > 0) stack.pop();
}
/**
* Creates a context key with a default value (React-style compatibility)
*
* @example
* ```ts
* const ThemeContext = createContext({ color: 'blue' })
* // ThemeContext is now typed as Context<{ color: string }>
* const theme = useContext(ThemeContext) // theme is { color: string }
* ```
*/
function createContext(defaultValue) {
	const key = Symbol("context");
	contextDefaults.set(key, defaultValue);
	return key;
}

//#endregion
//#region src/contexts/NodeTreeContext.ts
/**
* Context for having the current NodeTree
*/
const NodeTreeContext = createContext(null);

//#endregion
//#region src/createFile.ts
function combineSources(sources) {
	return uniqueBy(sources, (obj) => {
		var _ref;
		var _obj$name;
		var _obj$isExportable;
		var _obj$isTypeOnly;
		return `${(_ref = (_obj$name = obj.name) !== null && _obj$name !== void 0 ? _obj$name : obj.value) !== null && _ref !== void 0 ? _ref : ""}:${(_obj$isExportable = obj.isExportable) !== null && _obj$isExportable !== void 0 ? _obj$isExportable : false}:${(_obj$isTypeOnly = obj.isTypeOnly) !== null && _obj$isTypeOnly !== void 0 ? _obj$isTypeOnly : false}`;
	});
}
function combineExports(exports) {
	const sorted = orderBy(exports, [
		(v) => !!Array.isArray(v.name),
		(v) => !v.isTypeOnly,
		(v) => v.path,
		(v) => !!v.name,
		(v) => Array.isArray(v.name) ? orderBy(v.name) : v.name
	]);
	const prev = [];
	const pathMap = /* @__PURE__ */ new Map();
	const uniqueMap = /* @__PURE__ */ new Map();
	for (const curr of sorted) {
		const name = curr.name;
		const pathKey = curr.path;
		const prevByPath = pathMap.get(pathKey);
		const uniqueKey = `${`${pathKey}:${Array.isArray(name) ? JSON.stringify(name) : name || ""}:${curr.isTypeOnly}`}:${curr.asAlias || ""}`;
		if (uniqueMap.get(uniqueKey) || Array.isArray(name) && !name.length || (prevByPath === null || prevByPath === void 0 ? void 0 : prevByPath.asAlias) && !curr.asAlias) continue;
		if (!prevByPath) {
			const newItem = {
				...curr,
				name: Array.isArray(name) ? [...new Set(name)] : name
			};
			prev.push(newItem);
			pathMap.set(pathKey, newItem);
			uniqueMap.set(uniqueKey, newItem);
			continue;
		}
		if (prevByPath && Array.isArray(prevByPath.name) && Array.isArray(curr.name) && prevByPath.isTypeOnly === curr.isTypeOnly) {
			prevByPath.name = [...new Set([...prevByPath.name, ...curr.name])];
			continue;
		}
		prev.push(curr);
		uniqueMap.set(uniqueKey, curr);
	}
	return prev;
}
function combineImports(imports, exports, source) {
	const exportedNameLookup = /* @__PURE__ */ new Set();
	for (const item of exports) {
		const { name } = item;
		if (!name) continue;
		if (Array.isArray(name)) {
			for (const value of name) if (value) exportedNameLookup.add(value);
			continue;
		}
		exportedNameLookup.add(name);
	}
	const usageCache = /* @__PURE__ */ new Map();
	const hasImportInSource = (importName) => {
		if (!source) return true;
		const cached = usageCache.get(importName);
		if (cached !== void 0) return cached;
		const isUsed = source.includes(importName) || exportedNameLookup.has(importName);
		usageCache.set(importName, isUsed);
		return isUsed;
	};
	const sorted = orderBy(imports, [
		(v) => !!Array.isArray(v.name),
		(v) => !v.isTypeOnly,
		(v) => v.path,
		(v) => !!v.name,
		(v) => Array.isArray(v.name) ? orderBy(v.name) : v.name
	]);
	const prev = [];
	const pathTypeMap = /* @__PURE__ */ new Map();
	const uniqueMap = /* @__PURE__ */ new Map();
	for (const curr of sorted) {
		let name = Array.isArray(curr.name) ? [...new Set(curr.name)] : curr.name;
		if (curr.path === curr.root) continue;
		if (Array.isArray(name)) name = name.filter((item) => typeof item === "string" ? hasImportInSource(item) : hasImportInSource(item.propertyName));
		const pathTypeKey = `${curr.path}:${curr.isTypeOnly}`;
		const prevByPath = pathTypeMap.get(pathTypeKey);
		const nameKey = Array.isArray(name) ? JSON.stringify(name) : name || "";
		const pathNameTypeKey = `${curr.path}:${nameKey}:${curr.isTypeOnly}`;
		if (uniqueMap.get(pathNameTypeKey) || Array.isArray(name) && !name.length) continue;
		if (!prevByPath) {
			const newItem = {
				...curr,
				name
			};
			prev.push(newItem);
			pathTypeMap.set(pathTypeKey, newItem);
			uniqueMap.set(pathNameTypeKey, newItem);
			continue;
		}
		if (prevByPath && Array.isArray(prevByPath.name) && Array.isArray(name) && prevByPath.isTypeOnly === curr.isTypeOnly) {
			prevByPath.name = [...new Set([...prevByPath.name, ...name])];
			continue;
		}
		if (!Array.isArray(name) && name && !hasImportInSource(name)) continue;
		prev.push(curr);
		uniqueMap.set(pathNameTypeKey, curr);
	}
	return prev;
}
/**
* Helper to create a file with name and id set
*/
function createFile(file) {
	var _file$exports;
	var _file$imports;
	var _file$sources;
	const extname = path.extname(file.baseName);
	if (!extname) throw new Error(`No extname found for ${file.baseName}`);
	const source = file.sources.map((item) => item.value).join("\n\n");
	const exports = ((_file$exports = file.exports) === null || _file$exports === void 0 ? void 0 : _file$exports.length) ? combineExports(file.exports) : [];
	const imports = ((_file$imports = file.imports) === null || _file$imports === void 0 ? void 0 : _file$imports.length) && source ? combineImports(file.imports, exports, source) : [];
	const sources = ((_file$sources = file.sources) === null || _file$sources === void 0 ? void 0 : _file$sources.length) ? combineSources(file.sources) : [];
	return {
		...file,
		id: createHash("sha256").update(file.path).digest("hex"),
		name: trimExtName(file.baseName),
		extname,
		imports,
		exports,
		sources,
		meta: file.meta || {}
	};
}

//#endregion
//#region \0@oxc-project+runtime@0.112.0/helpers/checkPrivateRedeclaration.js
function _checkPrivateRedeclaration(e, t) {
	if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
}

//#endregion
//#region \0@oxc-project+runtime@0.112.0/helpers/classPrivateFieldInitSpec.js
function _classPrivateFieldInitSpec(e, t, a) {
	_checkPrivateRedeclaration(e, t), t.set(e, a);
}

//#endregion
//#region \0@oxc-project+runtime@0.112.0/helpers/assertClassBrand.js
function _assertClassBrand(e, t, n) {
	if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
	throw new TypeError("Private element is not present on this object");
}

//#endregion
//#region \0@oxc-project+runtime@0.112.0/helpers/classPrivateFieldGet2.js
function _classPrivateFieldGet2(s, a) {
	return s.get(_assertClassBrand(s, a));
}

//#endregion
//#region \0@oxc-project+runtime@0.112.0/helpers/classPrivateFieldSet2.js
function _classPrivateFieldSet2(s, a, r) {
	return s.set(_assertClassBrand(s, a), r), r;
}

//#endregion
//#region src/utils/AsyncEventEmitter.ts
var _emitter = /* @__PURE__ */ new WeakMap();
var _mode = /* @__PURE__ */ new WeakMap();
var AsyncEventEmitter = class {
	constructor({ maxListener = 100, mode = "sequential" } = {}) {
		_classPrivateFieldInitSpec(this, _emitter, new EventEmitter());
		_classPrivateFieldInitSpec(this, _mode, void 0);
		_classPrivateFieldGet2(_emitter, this).setMaxListeners(maxListener);
		_classPrivateFieldSet2(_mode, this, mode);
	}
	async emit(eventName, ...eventArgs) {
		const listeners = _classPrivateFieldGet2(_emitter, this).listeners(eventName);
		if (listeners.length === 0) return;
		const errors = [];
		if (_classPrivateFieldGet2(_mode, this) === "sequential") for (const listener of listeners) try {
			await listener(...eventArgs);
		} catch (err) {
			const error = err instanceof Error ? err : new Error(String(err));
			errors.push(error);
		}
		else {
			const promises = listeners.map(async (listener) => {
				try {
					await listener(...eventArgs);
				} catch (err) {
					const error = err instanceof Error ? err : new Error(String(err));
					errors.push(error);
				}
			});
			await Promise.all(promises);
		}
		if (errors.length === 1) throw errors[0];
		if (errors.length > 1) throw new AggregateError(errors, `Errors in async listeners for "${eventName}"`);
	}
	on(eventName, handler) {
		_classPrivateFieldGet2(_emitter, this).on(eventName, handler);
	}
	onOnce(eventName, handler) {
		const wrapper = (...args) => {
			this.off(eventName, wrapper);
			handler(...args);
		};
		this.on(eventName, wrapper);
	}
	off(eventName, handler) {
		_classPrivateFieldGet2(_emitter, this).off(eventName, handler);
	}
	removeAll() {
		_classPrivateFieldGet2(_emitter, this).removeAllListeners();
	}
};

//#endregion
//#region \0@oxc-project+runtime@0.112.0/helpers/typeof.js
function _typeof(o) {
	"@babel/helpers - typeof";
	return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
		return typeof o;
	} : function(o) {
		return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
	}, _typeof(o);
}

//#endregion
//#region \0@oxc-project+runtime@0.112.0/helpers/toPrimitive.js
function toPrimitive(t, r) {
	if ("object" != _typeof(t) || !t) return t;
	var e = t[Symbol.toPrimitive];
	if (void 0 !== e) {
		var i = e.call(t, r || "default");
		if ("object" != _typeof(i)) return i;
		throw new TypeError("@@toPrimitive must return a primitive value.");
	}
	return ("string" === r ? String : Number)(t);
}

//#endregion
//#region \0@oxc-project+runtime@0.112.0/helpers/toPropertyKey.js
function toPropertyKey(t) {
	var i = toPrimitive(t, "string");
	return "symbol" == _typeof(i) ? i : i + "";
}

//#endregion
//#region \0@oxc-project+runtime@0.112.0/helpers/defineProperty.js
function _defineProperty(e, r, t) {
	return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
		value: t,
		enumerable: !0,
		configurable: !0,
		writable: !0
	}) : e[r] = t, e;
}

//#endregion
//#region src/FileProcessor.ts
var _limit = /* @__PURE__ */ new WeakMap();
var FileProcessor = class {
	constructor({ events = new AsyncEventEmitter() } = {}) {
		_classPrivateFieldInitSpec(this, _limit, pLimit(100));
		_defineProperty(this, "events", void 0);
		this.events = events;
		return this;
	}
	async parse(file, { parsers, extension } = {}) {
		const parseExtName = (extension === null || extension === void 0 ? void 0 : extension[file.extname]) || void 0;
		if (!parsers) {
			console.warn("No parsers provided, using default parser. If you want to use a specific parser, please provide it in the options.");
			return defaultParser.parse(file, { extname: parseExtName });
		}
		if (!file.extname) return defaultParser.parse(file, { extname: parseExtName });
		const parser = parsers.get(file.extname);
		if (!parser) return defaultParser.parse(file, { extname: parseExtName });
		return parser.parse(file, { extname: parseExtName });
	}
	async run(files, { parsers, mode = "sequential", dryRun, extension } = {}) {
		await this.events.emit("files:processing:start", files);
		const total = files.length;
		let processed = 0;
		const processOne = async (resolvedFile, index) => {
			await this.events.emit("file:processing:start", resolvedFile, index, total);
			const source = dryRun ? void 0 : await this.parse(resolvedFile, {
				extension,
				parsers
			});
			const currentProcessed = ++processed;
			const percentage = currentProcessed / total * 100;
			await this.events.emit("file:processing:update", {
				file: resolvedFile,
				source,
				processed: currentProcessed,
				percentage,
				total
			});
			await this.events.emit("file:processing:end", resolvedFile, index, total);
		};
		if (mode === "sequential") {
			async function* asyncFiles() {
				for (let index = 0; index < files.length; index++) yield [files[index], index];
			}
			for await (const [file, index] of asyncFiles()) if (file) await processOne(file, index);
		} else {
			const promises = files.map((resolvedFile, index) => _classPrivateFieldGet2(_limit, this).call(this, () => processOne(resolvedFile, index)));
			await Promise.all(promises);
		}
		await this.events.emit("files:processing:end", files);
		return files;
	}
};

//#endregion
//#region src/utils/Cache.ts
var _buffer = /* @__PURE__ */ new WeakMap();
var Cache = class {
	constructor() {
		_classPrivateFieldInitSpec(this, _buffer, /* @__PURE__ */ new Map());
	}
	get(key) {
		var _this$buffer$get;
		return (_this$buffer$get = _classPrivateFieldGet2(_buffer, this).get(key)) !== null && _this$buffer$get !== void 0 ? _this$buffer$get : null;
	}
	set(key, value) {
		_classPrivateFieldGet2(_buffer, this).set(key, value);
	}
	delete(key) {
		_classPrivateFieldGet2(_buffer, this).delete(key);
	}
	clear() {
		_classPrivateFieldGet2(_buffer, this).clear();
	}
	keys() {
		return [..._classPrivateFieldGet2(_buffer, this).keys()];
	}
	values() {
		return [..._classPrivateFieldGet2(_buffer, this).values()];
	}
	flush() {}
};

//#endregion
//#region \0@oxc-project+runtime@0.112.0/helpers/classPrivateMethodInitSpec.js
function _classPrivateMethodInitSpec(e, a) {
	_checkPrivateRedeclaration(e, a), a.add(e);
}

//#endregion
//#region src/FileManager.ts
function mergeFile(a, b) {
	return {
		...a,
		sources: [...a.sources || [], ...b.sources || []],
		imports: [...a.imports || [], ...b.imports || []],
		exports: [...a.exports || [], ...b.exports || []]
	};
}
var _cache = /* @__PURE__ */ new WeakMap();
var _filesCache = /* @__PURE__ */ new WeakMap();
var _FileManager_brand = /* @__PURE__ */ new WeakSet();
var FileManager = class {
	constructor({ events = new AsyncEventEmitter() } = {}) {
		_classPrivateMethodInitSpec(this, _FileManager_brand);
		_classPrivateFieldInitSpec(this, _cache, new Cache());
		_classPrivateFieldInitSpec(this, _filesCache, null);
		_defineProperty(this, "events", void 0);
		_defineProperty(this, "processor", void 0);
		this.processor = new FileProcessor({ events });
		this.events = events;
		return this;
	}
	add(...files) {
		const resolvedFiles = [];
		const mergedFiles = /* @__PURE__ */ new Map();
		files.forEach((file) => {
			const existing = mergedFiles.get(file.path);
			if (existing) mergedFiles.set(file.path, mergeFile(existing, file));
			else mergedFiles.set(file.path, file);
		});
		for (let file of mergedFiles.values()) {
			file = _assertClassBrand(_FileManager_brand, this, _resolveName).call(this, file);
			file = _assertClassBrand(_FileManager_brand, this, _resolvePath).call(this, file);
			const resolvedFile = createFile(file);
			_classPrivateFieldGet2(_cache, this).set(resolvedFile.path, resolvedFile);
			this.flush();
			resolvedFiles.push(resolvedFile);
		}
		this.events.emit("files:added", resolvedFiles);
		return resolvedFiles;
	}
	upsert(...files) {
		const resolvedFiles = [];
		const mergedFiles = /* @__PURE__ */ new Map();
		files.forEach((file) => {
			const existing = mergedFiles.get(file.path);
			if (existing) mergedFiles.set(file.path, mergeFile(existing, file));
			else mergedFiles.set(file.path, file);
		});
		for (let file of mergedFiles.values()) {
			const existing = _classPrivateFieldGet2(_cache, this).get(file.path);
			file = _assertClassBrand(_FileManager_brand, this, _resolveName).call(this, file);
			file = _assertClassBrand(_FileManager_brand, this, _resolvePath).call(this, file);
			const resolvedFile = createFile(existing ? mergeFile(existing, file) : file);
			_classPrivateFieldGet2(_cache, this).set(resolvedFile.path, resolvedFile);
			this.flush();
			resolvedFiles.push(resolvedFile);
		}
		this.events.emit("files:added", resolvedFiles);
		return resolvedFiles;
	}
	flush() {
		_classPrivateFieldSet2(_filesCache, this, null);
		_classPrivateFieldGet2(_cache, this).flush();
	}
	getByPath(path) {
		return _classPrivateFieldGet2(_cache, this).get(path);
	}
	deleteByPath(path) {
		_classPrivateFieldGet2(_cache, this).delete(path);
		_classPrivateFieldSet2(_filesCache, this, null);
	}
	clear() {
		_classPrivateFieldGet2(_cache, this).clear();
		_classPrivateFieldSet2(_filesCache, this, null);
	}
	get files() {
		if (_classPrivateFieldGet2(_filesCache, this)) return _classPrivateFieldGet2(_filesCache, this);
		const keys = orderBy(_classPrivateFieldGet2(_cache, this).keys(), [(v) => v.length, (v) => trimExtName(v).endsWith("index")]);
		const files = [];
		for (const key of keys) {
			const file = _classPrivateFieldGet2(_cache, this).get(key);
			if (file) files.push(file);
		}
		_classPrivateFieldSet2(_filesCache, this, files);
		return files;
	}
	async write(options) {
		await this.events.emit("files:writing:start", this.files);
		const resolvedFiles = await this.processor.run(this.files, options);
		this.clear();
		await this.events.emit("files:writing:end", resolvedFiles);
		return resolvedFiles;
	}
};
function _resolvePath(file) {
	this.events.emit("file:resolve:path", file);
	return file;
}
function _resolveName(file) {
	this.events.emit("file:resolve:name", file);
	return file;
}

//#endregion
//#region src/utils/TreeNode.ts
var _childrenMap = /* @__PURE__ */ new WeakMap();
var _cachedLeaves = /* @__PURE__ */ new WeakMap();
var TreeNode = class TreeNode {
	constructor(data, parent) {
		_defineProperty(this, "data", void 0);
		_defineProperty(this, "parent", void 0);
		_defineProperty(this, "children", []);
		_classPrivateFieldInitSpec(this, _childrenMap, /* @__PURE__ */ new Map());
		_classPrivateFieldInitSpec(this, _cachedLeaves, void 0);
		this.data = data;
		this.parent = parent;
	}
	addChild(data) {
		const child = new TreeNode(data, this);
		this.children.push(child);
		if (typeof data === "object" && data !== null && "name" in data) _classPrivateFieldGet2(_childrenMap, this).set(data.name, child);
		_classPrivateFieldSet2(_cachedLeaves, this, void 0);
		return child;
	}
	getChildByName(name) {
		return _classPrivateFieldGet2(_childrenMap, this).get(name);
	}
	get leaves() {
		if (_classPrivateFieldGet2(_cachedLeaves, this)) return _classPrivateFieldGet2(_cachedLeaves, this);
		if (this.children.length === 0) return [this];
		const result = [];
		const stack = [...this.children];
		const visited = /* @__PURE__ */ new Set();
		while (stack.length > 0) {
			const node = stack.pop();
			if (visited.has(node)) continue;
			visited.add(node);
			if (node.children.length > 0) stack.push(...node.children);
			else result.push(node);
		}
		_classPrivateFieldSet2(_cachedLeaves, this, result);
		return result;
	}
	forEach(callback) {
		const stack = [this];
		for (let i = 0; i < stack.length; i++) {
			const node = stack[i];
			callback(node);
			if (node.children.length > 0) stack.push(...node.children);
		}
		return this;
	}
	findDeep(predicate) {
		for (const leaf of this.leaves) if (predicate(leaf)) return leaf;
	}
	static toGraph(root) {
		const nodes = [];
		const edges = [];
		const stack = [root];
		for (let i = 0; i < stack.length; i++) {
			const node = stack[i];
			nodes.push({
				id: node.data.path,
				label: node.data.name
			});
			const children = node.children;
			if (children.length > 0) for (let j = 0, len = children.length; j < len; j++) {
				const child = children[j];
				edges.push({
					from: node.data.path,
					to: child.data.path
				});
				stack.push(child);
			}
		}
		return {
			nodes,
			edges
		};
	}
	static fromFiles(files, rootFolder = "") {
		const normalizePath = (p) => p.replace(/\\/g, "/");
		const normalizedRoot = normalizePath(rootFolder);
		const rootPrefix = normalizedRoot.endsWith("/") ? normalizedRoot : `${normalizedRoot}/`;
		const normalizedPaths = /* @__PURE__ */ new Map();
		const filteredFiles = [];
		for (const file of files) {
			var _normalizedPaths$get;
			const filePath = (_normalizedPaths$get = normalizedPaths.get(file)) !== null && _normalizedPaths$get !== void 0 ? _normalizedPaths$get : normalizePath(file.path);
			normalizedPaths.set(file, filePath);
			if (!filePath.endsWith(".json") && (!rootFolder || filePath.startsWith(rootPrefix))) filteredFiles.push(file);
		}
		if (filteredFiles.length === 0) return null;
		const treeNode = new TreeNode({
			name: rootFolder || "",
			path: rootFolder || "",
			file: void 0
		});
		for (const file of filteredFiles) {
			const parts = normalizedPaths.get(file).slice(rootPrefix.length).split("/");
			let current = treeNode;
			let currentPath = rootFolder;
			for (const [index, part] of parts.entries()) {
				const isLast = index === parts.length - 1;
				currentPath += (currentPath.endsWith("/") ? "" : "/") + part;
				let next = current.getChildByName(part);
				if (!next) next = current.addChild({
					name: part,
					path: currentPath,
					file: isLast ? file : void 0
				});
				current = next;
			}
		}
		return treeNode;
	}
};

//#endregion
//#region src/contexts/RootContext.ts
/**
* Context providing root-level functionalities such as exit hook, tree node structure, and file management.
* Define in the `render` helper of the runtime.
*/
const RootContext = createContext({
	exit: () => {},
	treeNode: new TreeNode({
		type: "Root",
		props: {}
	}),
	fileManager: new FileManager()
});

//#endregion
//#region src/contexts/RenderContext.ts
/**
* Provides a context for tracking rendering state such as indentation and line length.
*/
const RenderContext = createContext({
	indentLevel: 0,
	indentSize: 2,
	currentLineLength: 0,
	shouldBreak: false
});

//#endregion
//#region src/intrinsic.ts
function isFabricElement(value) {
	return typeof value === "function" && "type" in value && "component" in value;
}
/**
* Type guard to check if a value is an intrinsic element
*/
function isIntrinsic(value) {
	return value && typeof value === "object" && value.__intrinsic === true;
}
/**
* Render a single intrinsic node
*/
function renderIntrinsicNode(node, renderContext) {
	switch (node.type) {
		case "br":
			renderContext.currentLineLength = 0;
			return "\n";
		case "indent":
			renderContext.indentLevel++;
			return "";
		case "dedent":
			renderContext.indentLevel = Math.max(0, renderContext.indentLevel - 1);
			return "";
		default: return "";
	}
}
/**
* Helper: render a plain string while applying current indentation at the
* start of each logical line. This ensures `${indent}` intrinsics affect
* subsequent string content.
*/
function renderIndent(content, renderContext) {
	if (content.length === 0) return "";
	const indentStr = " ".repeat(renderContext.indentLevel * renderContext.indentSize);
	const lines = content.split("\n");
	let out = "";
	for (const [i, line] of lines.entries()) {
		if (renderContext.currentLineLength === 0 && line.length > 0) {
			out += indentStr + line;
			renderContext.currentLineLength = indentStr.length + line.length;
		} else {
			out += line;
			renderContext.currentLineLength += line.length;
		}
		if (i !== lines.length - 1) {
			out += "\n";
			renderContext.currentLineLength = 0;
		}
	}
	return out;
}
function renderIntrinsic(children, context) {
	const renderContext = context || inject(RenderContext);
	provide(RenderContext, renderContext);
	if (!children) return "";
	if (isFabricElement(children)) try {
		return renderIntrinsic(children());
	} catch {
		return "";
	}
	if (Array.isArray(children)) return children.map((child) => renderIntrinsic(child)).join("");
	if (isIntrinsic(children)) return renderIntrinsicNode(children, renderContext);
	if (typeof children === "function") return renderIntrinsic(children());
	if (typeof children === "string") return renderIndent(children, renderContext);
	if (typeof children === "number") return renderIndent(String(children), renderContext);
	if (typeof children === "boolean") return renderIndent(children ? "true" : "false", renderContext);
	try {
		return renderIndent(children, renderContext);
	} catch {
		return "";
	}
}
/**
* Create an intrinsic element
*/
function createIntrinsic(type) {
	return {
		type,
		__intrinsic: true
	};
}

//#endregion
//#region src/createComponent.ts
function createComponent(type, Component) {
	return (...args) => {
		const fn = (() => renderIntrinsic(Component(args[0])));
		fn.component = Component;
		fn.props = args[0];
		fn.type = type;
		fn.children = (...children) => {
			var _args$;
			const propsWithChildren = {
				...(_args$ = args[0]) !== null && _args$ !== void 0 ? _args$ : {},
				children() {
					return renderIntrinsic(children);
				}
			};
			const fnChild = (() => renderIntrinsic(Component(propsWithChildren)));
			fnChild.component = Component;
			fnChild.props = args[0];
			fnChild.type = type;
			return fnChild;
		};
		return fn;
	};
}

//#endregion
//#region src/components/Root.ts
/**
* Root component providing core Fabric runtime context.
*
* This component is typically used internally by the Fabric renderer.
* It provides the root context including FileManager, error handling,
* and lifecycle management.
*
* @example
* ```tsx
* <Root
*   onExit={(error) => process.exit(error ? 1 : 0)}
*   onError={(error) => console.error(error)}
*   treeNode={treeNode}
*   fileManager={fileManager}
* >
*   <App>
*     Your components here
*   </App>
* </Root>
* ```
*/
const Root = createComponent("Root", ({ onError, onExit, treeNode, fileManager, children }) => {
	provide(RootContext, {
		exit: onExit,
		treeNode,
		fileManager
	});
	provide(NodeTreeContext, treeNode);
	try {
		return children;
	} catch (e) {
		if (e instanceof Error) onError === null || onError === void 0 || onError(e);
		return "";
	}
});
Root.displayName = "Root";

//#endregion
export { NodeTreeContext as _, renderIntrinsic as a, provide as b, TreeNode as c, _defineProperty as d, AsyncEventEmitter as f, createFile as g, _classPrivateFieldInitSpec as h, renderIndent as i, FileManager as l, _classPrivateFieldGet2 as m, createComponent as n, RenderContext as o, _classPrivateFieldSet2 as p, createIntrinsic as r, RootContext as s, Root as t, FileProcessor as u, createContext as v, unprovide as x, inject as y };
//# sourceMappingURL=Root-BQX3eHqb.js.map