import { createRequire } from 'node:module';
import { AsyncLocalStorage } from 'node:async_hooks';

//#region ../lafs/dist/src/tokenEstimator.js
/**
* LAFS Token Estimator
*
* Provides character-based token estimation for LAFS envelopes and JSON payloads.
* Uses the approximation: 1 token ≈ 4 characters.
* Properly handles nested objects, arrays, Unicode graphemes, and circular references.
*/
/**
* Count Unicode graphemes in a string.
*
* @param str - Input string to count
* @returns Number of grapheme clusters in the string
*
* @remarks
* Uses `Intl.Segmenter` when available (Node.js 16+, modern browsers) for
* accurate grapheme counting. Falls back to spread-based code-point counting
* which handles surrogate pairs but not all grapheme clusters.
*/
function countGraphemes(str) {
	if (typeof Intl !== "undefined" && "Segmenter" in Intl) {
		const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
		return Array.from(segmenter.segment(str)).length;
	}
	return [...str].length;
}
/**
* Default options for token estimation.
*
* @remarks
* These values represent the baseline configuration used when no overrides
* are provided to the {@link TokenEstimator} constructor.
*/
var DEFAULT_OPTIONS = {
	charsPerToken: 4,
	maxDepth: 100,
	maxStringLength: 1e5
};
/**
* Character-based token estimator for JSON payloads.
*
* @remarks
* Algorithm:
* 1. Recursively traverse the value (handling circular refs via WeakSet)
* 2. Count Unicode graphemes (not bytes) for string content
* 3. Divide by `charsPerToken` ratio (default 4)
* 4. Add overhead for structural JSON characters
*
* The estimator is intentionally conservative to avoid underestimating budget usage.
*
* @example
* ```typescript
* const estimator = new TokenEstimator({ charsPerToken: 4 });
* const tokens = estimator.estimate({ name: "hello", items: [1, 2, 3] });
* ```
*/
var TokenEstimator = class {
	/** Resolved configuration with defaults applied */
	options;
	/**
	* Create a new TokenEstimator.
	*
	* @param options - Configuration overrides (merged with defaults)
	*/
	constructor(options = {}) {
		this.options = {
			...DEFAULT_OPTIONS,
			...options
		};
	}
	/**
	* Estimate tokens for any JavaScript value.
	* Handles circular references, nested objects, arrays, and Unicode.
	*
	* @param value - Any value to estimate
	* @returns Estimated token count
	*/
	estimate(value) {
		return this.estimateWithTracking(value, /* @__PURE__ */ new WeakSet(), 0);
	}
	/**
	* Estimate tokens from a JSON string.
	* More efficient if you already have the JSON string.
	*
	* @param json - JSON string to estimate
	* @returns Estimated token count
	*/
	estimateJSON(json) {
		const graphemes = countGraphemes(json);
		const structuralOverhead = Math.ceil(graphemes * .1);
		return Math.ceil((graphemes + structuralOverhead) / this.options.charsPerToken);
	}
	/**
	* Internal recursive estimation with circular reference tracking.
	*
	* @param value - Value to estimate
	* @param seen - WeakSet tracking visited objects for circular reference detection
	* @param depth - Current recursion depth
	* @returns Estimated token count for this value
	*/
	estimateWithTracking(value, seen, depth) {
		if (depth > this.options.maxDepth) return 1;
		if (value === null) return 1;
		if (value === void 0) return 1;
		const type = typeof value;
		if (type === "boolean") return value ? 1 : 1;
		if (type === "number") return Math.ceil(countGraphemes(String(value)) / this.options.charsPerToken);
		if (type === "string") {
			const str = value;
			const graphemes = countGraphemes(str.length > this.options.maxStringLength ? str.slice(0, this.options.maxStringLength) + "…" : str);
			return Math.ceil((graphemes + 2) / this.options.charsPerToken);
		}
		if (type === "object") {
			const obj = value;
			if (seen.has(obj)) return 1;
			seen.add(obj);
			try {
				if (Array.isArray(obj)) return this.estimateArray(obj, seen, depth);
				return this.estimateObject(obj, seen, depth);
			} finally {
				seen.delete(obj);
			}
		}
		return 1;
	}
	/**
	* Estimate tokens for an array.
	*
	* @param arr - Array to estimate
	* @param seen - WeakSet tracking visited objects
	* @param depth - Current recursion depth
	* @returns Estimated token count including brackets and separators
	*/
	estimateArray(arr, seen, depth) {
		let tokens = 1;
		for (let i = 0; i < arr.length; i++) {
			tokens += this.estimateWithTracking(arr[i], seen, depth + 1);
			if (i < arr.length - 1) tokens += 1;
		}
		tokens += 1;
		return tokens;
	}
	/**
	* Estimate tokens for a plain object.
	*
	* @param obj - Object to estimate
	* @param seen - WeakSet tracking visited objects
	* @param depth - Current recursion depth
	* @returns Estimated token count including braces, keys, colons, and separators
	*/
	estimateObject(obj, seen, depth) {
		let tokens = 1;
		const keys = Object.keys(obj);
		for (let i = 0; i < keys.length; i++) {
			const key = keys[i];
			const value = obj[key];
			tokens += Math.ceil((countGraphemes(key) + 2) / this.options.charsPerToken);
			tokens += 1;
			tokens += this.estimateWithTracking(value, seen, depth + 1);
			if (i < keys.length - 1) tokens += 1;
		}
		tokens += 1;
		return tokens;
	}
	/**
	* Check if a value can be safely serialized (no circular refs).
	*
	* @param value - Value to check
	* @returns `true` if `JSON.stringify` succeeds without throwing
	*/
	canSerialize(value) {
		try {
			JSON.stringify(value);
			return true;
		} catch {
			return false;
		}
	}
	/**
	* Serialize a value to JSON with circular reference handling.
	*
	* @param value - Value to serialize
	* @returns JSON string with circular references replaced by `"[Circular]"`
	*/
	safeStringify(value) {
		const seen = /* @__PURE__ */ new WeakSet();
		return JSON.stringify(value, (key, val) => {
			if (typeof val === "object" && val !== null) {
				if (seen.has(val)) return "[Circular]";
				seen.add(val);
			}
			return val;
		});
	}
	/**
	* Create a deep copy of a value with circular refs replaced by `"[Circular]"`.
	*
	* @param value - Value to copy
	* @returns Deep clone with all circular references replaced
	*/
	safeCopy(value) {
		const seen = /* @__PURE__ */ new WeakSet();
		function clone(val) {
			if (val === null || typeof val !== "object") return val;
			if (seen.has(val)) return "[Circular]";
			seen.add(val);
			try {
				if (Array.isArray(val)) return val.map(clone);
				const result = {};
				for (const [k, v] of Object.entries(val)) result[k] = clone(v);
				return result;
			} finally {
				seen.delete(val);
			}
		}
		return clone(value);
	}
};
new TokenEstimator();
//#endregion
//#region ../lafs/dist/src/envelope.js
/**
* AsyncLocalStorage carrier holding the active {@link WarningCollector}, if any.
*
* @remarks
* Exported so adapters that need to inspect (or temporarily replace) the
* active collector can do so without instantiating their own ALS. Most
* producers should use {@link pushWarning} and most adapters should use
* {@link withWarningCollector} instead of touching this directly.
*
* @public
*/
var currentWarningCollector = new AsyncLocalStorage();
/**
* Attach a non-fatal warning to the active operation's envelope.
*
* @param warning - The {@link Warning} to attach.
*
* @remarks
* No-op when there is no active {@link WarningCollector} bound via
* {@link withWarningCollector}. This means CORE / library code can call
* `pushWarning` unconditionally without checking whether it is running
* under a CLI adapter, a test harness, or an SDK consumer that has not yet
* adopted the carrier.
*
* @example
* ```ts
* import { pushWarning } from '@cleocode/lafs';
*
* try {
*   await writeBridge(...);
* } catch (err) {
*   pushWarning({
*     code: 'W_BRIDGE_WRITE_FAILED',
*     message: 'memory bridge write failed',
*     severity: 'warn',
*     context: { error: err instanceof Error ? err.message : String(err) },
*   });
* }
* ```
*
* @public
*/
function pushWarning(warning) {
	const collector = currentWarningCollector.getStore();
	if (collector) collector.push(warning);
}
//#endregion
//#region ../lafs/dist/src/health/index.js
/**
* LAFS Health Check Module
*
* Provides health check endpoints for monitoring and orchestration.
*
* @packageDocumentation
*/
var require$1 = createRequire(import.meta.url);
try {
	try {
		require$1("../../package.json");
	} catch {
		require$1("../../../package.json");
	}
} catch {}

export { pushWarning as p };
//# sourceMappingURL=src2-DK8DKufK.js.map
