// Worker protocol 基础（Phase 1 引擎抽象与 Worker 化）。
// 所有 Worker 内/外消息统一携带 sessionId + sequence；
// 旧 session、旧 sequence 或不匹配 session generation 的结果必须直接丢弃。
// 音频帧通过 postMessage 的 transferable ArrayBuffer 传递，不经过 Chrome Runtime JSON 序列化。
export function isWorkerEnvelope(value) {
    return typeof value === "object" && value !== null && typeof value.sessionId === "string" && typeof value.sequence === "number";
}
export function isWorkerRequestMessage(value) {
    if (!isWorkerEnvelope(value) || !("request" in value))
        return false;
    const request = value.request;
    return typeof request === "object" && request !== null;
}
export function isWorkerResponseMessage(value) {
    if (!isWorkerEnvelope(value) || !("response" in value))
        return false;
    const response = value.response;
    if (typeof response !== "object" || response === null)
        return false;
    const candidate = response;
    return typeof candidate.ok === "boolean" && (candidate.ok === true || typeof candidate.error === "string");
}
export function isWorkerEventMessage(value) {
    if (!isWorkerEnvelope(value) || !("event" in value))
        return false;
    const event = value.event;
    return typeof event === "object" && event !== null;
}
export function encodeWorkerRequest(sessionId, sequence, request) {
    return { sessionId, sequence, request };
}
export function encodeWorkerResponse(sessionId, sequence, response) {
    return { sessionId, sequence, response };
}
export function encodeWorkerEvent(sessionId, sequence, event) {
    return { sessionId, sequence, event };
}
export function createSequenceCounter() {
    let value = 0;
    return () => ++value;
}
export function createSessionId() {
    return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
export function isOkResponse(response) {
    return response.ok === true;
}
export function failureResponse(error) {
    return { ok: false, error };
}
export function successResponse(result) {
    return { ok: true, result };
}
