// ../packages/timeline/dist/index.js
function createTimelineSequencer(options) {
  let seq = options.startSeq ?? 0;
  const now = options.now ?? Date.now;
  return {
    append(item, rawRef) {
      seq += 1;
      return appendTimelineItem({
        sessionId: options.sessionId,
        provider: options.provider,
        epoch: options.epoch,
        seq,
        timestamp: now(),
        item,
        rawRef
      });
    }
  };
}
function appendTimelineItem(envelope) {
  return {
    ...envelope,
    rawRef: envelope.rawRef ? { ...envelope.rawRef } : void 0
  };
}
function createTimelineCursor(cursor) {
  return {
    epoch: cursor.epoch,
    afterSeq: cursor.afterSeq
  };
}
function fetchTimeline(timeline, request = {}) {
  const ordered = sortTimeline(timeline);
  const cursor = request.cursor ?? cursorFromTimelineStart(ordered);
  const items = ordered.filter((item) => item.epoch === cursor.epoch && item.seq > cursor.afterSeq).slice(0, request.limit);
  const lastSeq = items.at(-1)?.seq ?? cursor.afterSeq;
  const firstSeq = items[0]?.seq;
  return {
    items,
    nextCursor: {
      epoch: cursor.epoch,
      afterSeq: lastSeq
    },
    hasGap: firstSeq !== void 0 && firstSeq > cursor.afterSeq + 1
  };
}
function mergeTimeline(existing, incoming) {
  const byKey = /* @__PURE__ */ new Map();
  for (const item of [...existing, ...incoming]) {
    byKey.set(timelineKey(item), item);
  }
  return sortTimeline([...byKey.values()]);
}
function cursorFromTimelineStart(timeline) {
  return {
    epoch: timeline[0]?.epoch ?? "default",
    afterSeq: 0
  };
}
function sortTimeline(timeline) {
  return [...timeline].sort((left, right) => {
    if (left.epoch !== right.epoch) return left.epoch.localeCompare(right.epoch);
    return left.seq - right.seq;
  });
}
function timelineKey(item) {
  return `${item.epoch}:${item.seq}`;
}

export {
  createTimelineSequencer,
  appendTimelineItem,
  createTimelineCursor,
  fetchTimeline,
  mergeTimeline
};
