const require_constants = require("../constants.cjs");
const require_message_coercion = require("../message-coercion.cjs");
const require_namespace = require("../namespace.cjs");
const require_runtime = require("./runtime.cjs");
//#region src/stream/projections/values.ts
function valuesProjection(namespace, messagesKey = require_constants.DEFAULT_MESSAGES_KEY) {
	const ns = [...namespace];
	return {
		key: `values|${messagesKey}|${require_namespace.namespaceKey(ns)}`,
		namespace: ns,
		initial: void 0,
		open({ thread, store, rootBus }) {
			const applyValuesEvent = (event) => {
				const coerced = coerceMessagesInState(event.params.data, messagesKey);
				store.setValue(coerced);
			};
			if (require_namespace.isRootNamespace(ns) && rootBus.channels.includes("values")) {
				const unsubscribe = rootBus.subscribe((event) => {
					if (event.method !== "values") return;
					if (!require_namespace.isRootNamespace(event.params.namespace)) return;
					applyValuesEvent(event);
				});
				return { dispose() {
					unsubscribe();
				} };
			}
			return require_runtime.openProjectionSubscription({
				thread,
				channels: ["values"],
				namespace: ns,
				onEvent(event) {
					if (event.method !== "values") return;
					applyValuesEvent(event);
				}
			});
		}
	};
}
function coerceMessagesInState(value, messagesKey) {
	if (value == null || typeof value !== "object" || Array.isArray(value)) return value;
	const state = value;
	const maybeMessages = state[messagesKey];
	if (!Array.isArray(maybeMessages) || maybeMessages.length === 0) return value;
	if (!maybeMessages.some((m) => m != null && typeof m.getType !== "function")) return value;
	return {
		...state,
		[messagesKey]: require_message_coercion.ensureMessageInstances(maybeMessages)
	};
}
//#endregion
exports.valuesProjection = valuesProjection;

//# sourceMappingURL=values.cjs.map