{"version":3,"file":"cloudHub.mjs","names":[],"sources":["../../../src/web/lib/cloudHub.ts"],"sourcesContent":["import { WORKSPACES_API_ROUTE, type SessionSummary, type WorkspaceSummary } from '../../types/hub';\nimport { qualifyHostId } from './hostIdentity';\nimport { asWorkspace } from './workspaceSummary';\n\n/** The cloud lists what its org owns; the client asks again on this cadence. */\nexport const CLOUD_HUB_POLL_MS = 15_000;\n\n/** What a Po Cloud org answers, keyed in the runtime namespace of the host record that reaches it. */\nexport interface CloudHubSnapshot {\n  workspaces: WorkspaceSummary[];\n  sessions: SessionSummary[];\n}\n\n/** The caller owns credentials: it adds the session cookie and org header, never this module. */\nexport type CloudHubFetch = (\n  url: string,\n  init?: { method?: string; headers?: Record<string, string>; body?: string; signal?: AbortSignal },\n) => Promise<Response>;\n\nexport interface CloudHubOptions {\n  /** The canonical host UUID the views are qualified with. */\n  hostId: string;\n  /** HTTPS origin of the Po Cloud worker. */\n  origin: string;\n  fetch: CloudHubFetch;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nasync function failure(response: Response): Promise<Error> {\n  const text = await response.text().catch(() => '');\n  let message = text;\n  try {\n    const body: unknown = JSON.parse(text);\n    if (isRecord(body) && typeof body.error === 'string') message = body.error;\n  } catch {\n    // Cloud refusals are plain text; the text itself is the message.\n  }\n  return new Error(message.trim() || `Po Cloud answered ${response.status}.`);\n}\n\n/**\n * Lists a Po Cloud org's workspaces and sessions over plain HTTP. DOM-free: phones and the desktop\n * inject their own fetch, which carries the identity cookie and `x-po-org`.\n */\nexport function createCloudHub(options: CloudHubOptions) {\n  const base = options.origin.replace(/\\/+$/u, '');\n  const workspacePath = (workspaceId: string) => `${base}${WORKSPACES_API_ROUTE}/${encodeURIComponent(workspaceId)}`;\n  const qualify = (id: string) => qualifyHostId(options.hostId, id);\n  const local = (id: string) => (id.startsWith(`${options.hostId}/`) ? id.slice(options.hostId.length + 1) : id);\n\n  const readJson = async (url: string, signal?: AbortSignal): Promise<unknown> => {\n    const response = await options.fetch(url, signal === undefined ? { method: 'GET' } : { method: 'GET', signal });\n    if (!response.ok) throw await failure(response);\n    return response.json();\n  };\n\n  const listSessions = async (workspaceId: string, signal?: AbortSignal): Promise<SessionSummary[]> => {\n    const body = await readJson(`${workspacePath(workspaceId)}/sessions`, signal);\n    if (!isRecord(body) || !Array.isArray(body.sessions)) throw new Error('Po Cloud returned an invalid session list.');\n    return body.sessions.flatMap((session) =>\n      isRecord(session) && typeof session.id === 'string' && typeof session.name === 'string'\n        ? [{ ...(session as unknown as SessionSummary), id: qualify(session.id), workspaceId: qualify(workspaceId) }]\n        : [],\n    );\n  };\n\n  const list = async (signal?: AbortSignal): Promise<CloudHubSnapshot> => {\n    const body = await readJson(`${base}${WORKSPACES_API_ROUTE}`, signal);\n    if (!isRecord(body) || !Array.isArray(body.workspaces))\n      throw new Error('Po Cloud returned an invalid workspace list.');\n    const local = body.workspaces.map(asWorkspace).filter((entry): entry is WorkspaceSummary => entry !== undefined);\n    // One unreadable workspace fails the whole list, so a partial answer never drops live sessions.\n    const sessions = await Promise.all(local.map((workspace) => listSessions(workspace.id, signal)));\n    return {\n      workspaces: local.map((workspace) => ({ ...workspace, id: qualify(workspace.id) })),\n      sessions: sessions.flat(),\n    };\n  };\n\n  return {\n    list,\n    /** Starts a cloud session in one of this org's workspaces and returns its qualified id. */\n    async createSession(workspaceId: string, name?: string): Promise<string> {\n      const response = await options.fetch(`${workspacePath(local(workspaceId))}/sessions`, {\n        method: 'POST',\n        headers: { 'content-type': 'application/json' },\n        body: JSON.stringify(name === undefined ? {} : { name }),\n      });\n      if (!response.ok) throw await failure(response);\n      const body: unknown = await response.json();\n      if (!isRecord(body) || typeof body.sessionId !== 'string')\n        throw new Error('Po Cloud returned an invalid session.');\n      return qualify(body.sessionId);\n    },\n    /** Deletes one cloud session; both ids may be qualified. */\n    async deleteSession(workspaceId: string, sessionId: string): Promise<void> {\n      const response = await options.fetch(\n        `${workspacePath(local(workspaceId))}/sessions/${encodeURIComponent(local(sessionId))}`,\n        { method: 'DELETE' },\n      );\n      if (!response.ok) throw await failure(response);\n    },\n    /**\n     * Lists now, then again every interval until stopped. A failed round reports and keeps polling.\n     * `subscribe` hands out a refresh that lists at once, for a host that says when its list changed.\n     */\n    poll(handlers: {\n      onSnapshot(snapshot: CloudHubSnapshot): void;\n      onError?(error: Error): void;\n      intervalMs?: number;\n      subscribe?(refresh: () => void): () => void;\n    }): () => void {\n      const controller = new AbortController();\n      let timer: ReturnType<typeof setTimeout> | undefined;\n      let running = false;\n      let stale = false;\n      const round = async () => {\n        running = true;\n        stale = false;\n        try {\n          const snapshot = await list(controller.signal);\n          if (!controller.signal.aborted) handlers.onSnapshot(snapshot);\n        } catch (error) {\n          if (!controller.signal.aborted)\n            handlers.onError?.(error instanceof Error ? error : new Error('Po Cloud is unreachable.'));\n        }\n        running = false;\n        if (controller.signal.aborted) return;\n        // A change reported during the round may have missed its answer, so the list is read once more.\n        if (stale) void round();\n        else timer = setTimeout(() => void round(), handlers.intervalMs ?? CLOUD_HUB_POLL_MS);\n      };\n      void round();\n      const unsubscribe = handlers.subscribe?.(() => {\n        if (controller.signal.aborted) return;\n        if (running) {\n          stale = true;\n          return;\n        }\n        if (timer !== undefined) clearTimeout(timer);\n        void round();\n      });\n      return () => {\n        unsubscribe?.();\n        controller.abort();\n        if (timer !== undefined) clearTimeout(timer);\n      };\n    },\n  };\n}\n\nexport type CloudHub = ReturnType<typeof createCloudHub>;\n"],"mappings":";;;;;AAKA,MAAa,oBAAoB;AAsBjC,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,eAAe,QAAQ,UAAoC;CACzD,MAAM,OAAO,MAAM,SAAS,KAAK,CAAC,CAAC,YAAY,EAAE;CACjD,IAAI,UAAU;CACd,IAAI;EACF,MAAM,OAAgB,KAAK,MAAM,IAAI;EACrC,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