import "../../shared/src/valita.js";
import { clientSchemaSchema } from "./client-schema.js";
import { deleteClientsBodySchema } from "./delete-clients.js";
import { upQueriesPatchSchema } from "./queries-patch.js";
import { object, number, string, tuple, literal, array, record } from "@badrap/valita";
const connectedBodySchema = object({
  wsid: string(),
  timestamp: number().optional()
});
const connectedMessageSchema = tuple([
  literal("connected"),
  connectedBodySchema
]);
const initConnectionBodySchema = object({
  desiredQueriesPatch: upQueriesPatchSchema,
  // As the schema can be large, client only sends when it does not have a
  // server snapshot (i.e. a snapshot with a cookie).  Once it has a server
  // snapshot it will assume the zero-cache already has the schema for this
  // client's client group in the CVR store.
  clientSchema: clientSchemaSchema.optional(),
  deleted: deleteClientsBodySchema.optional(),
  // parameters to configure the mutate endpoint
  userPushURL: string().optional(),
  userPushHeaders: record(string()).optional(),
  // parameters to configure the query endpoint
  userQueryURL: string().optional(),
  userQueryHeaders: record(string()).optional(),
  /**
   * `activeClients` is an optional array of client IDs that are currently active
   * in the client group. This is used to inform the server about the clients
   * that are currently active (aka running, aka alive), so it can inactive
   * queries from inactive clients.
   */
  activeClients: array(string()).optional()
});
const initConnectionMessageSchema = tuple([
  literal("initConnection"),
  initConnectionBodySchema
]);
function encodeSecProtocols(initConnectionMessage, authToken) {
  const protocols = {
    initConnectionMessage,
    authToken
  };
  const bytes = new TextEncoder().encode(JSON.stringify(protocols));
  const s = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
  return encodeURIComponent(btoa(s));
}
function decodeSecProtocols(secProtocol) {
  const binString = atob(decodeURIComponent(secProtocol));
  const bytes = Uint8Array.from(binString, (c) => c.charCodeAt(0));
  return JSON.parse(new TextDecoder().decode(bytes));
}
export {
  connectedBodySchema,
  connectedMessageSchema,
  decodeSecProtocols,
  encodeSecProtocols,
  initConnectionMessageSchema
};
//# sourceMappingURL=connect.js.map
