require("../../../_virtual/_rolldown/runtime.js");
let react = require("react");
//#region src/plus/salesSdk/hooks/useSyncOsModule.ts
/**
* 浅比较两个对象的"自身可枚举属性"。null/undefined 视作空对象。
*/
function shallowEqual(a, b) {
	if (Object.is(a, b)) return true;
	if (typeof a !== "object" || a === null || typeof b !== "object" || b === null) return false;
	const ka = Object.keys(a);
	const kb = Object.keys(b);
	if (ka.length !== kb.length) return false;
	for (const k of ka) {
		if (!Object.prototype.hasOwnProperty.call(b, k)) return false;
		if (!Object.is(a[k], b[k])) return false;
	}
	return true;
}
/**
* 通用 useSyncExternalStore 适配 OS effects 事件。
*
* 设计点：
*  - subscribe 通过 `module.effectsOn(evt, onStoreChange)` 注册多事件，返回组合 cleanup。
*  - getSnapshot 在 React 内部维护 lastSnapshotRef + isEqual 浅比较，确保未变更时返回稳定引用，
*    避免 React 18 在 useSyncExternalStore 中因引用变化反复 tear（getServerSnapshot 同体引用）。
*  - 调用方传入的 events 数组用 join('|') 作为 subscribe 依赖项，避免数组每次新引用导致重订阅。
*
* 示例：
*   const data = useSyncOsModule(
*     bookingTicket,
*     ['onSalesOrderLoaded'],
*     () => ({
*       tempOrder: bookingTicket?.getTempOrder() ?? null,
*       summary: bookingTicket?.getSalesOrder()?.summary ?? null,
*     }),
*   );
*/
function useSyncOsModule(module, events, getSnapshot, isEqual = shallowEqual) {
	const lastSnapshotRef = (0, react.useRef)({
		value: void 0,
		initialized: false
	});
	const stableGetSnapshot = (0, react.useCallback)(() => {
		const next = getSnapshot();
		const cache = lastSnapshotRef.current;
		if (!cache.initialized) {
			cache.value = next;
			cache.initialized = true;
			return next;
		}
		if (isEqual(cache.value, next)) return cache.value;
		cache.value = next;
		return next;
	}, [isEqual]);
	return (0, react.useSyncExternalStore)((0, react.useCallback)((onStoreChange) => {
		if (!module) return () => {};
		const offs = events.map((evt) => module.effectsOn(evt, onStoreChange));
		return () => {
			for (const off of offs) try {
				off();
			} catch (_unused) {}
		};
	}, [module, events.join("|")]), stableGetSnapshot, stableGetSnapshot);
}
//#endregion
exports.useSyncOsModule = useSyncOsModule;
