import { z } from "zod";
import { jwtDecode } from "jwt-decode";
const ApiHandlerHeaders = {
  SiteVersion: "X-Makeswift-Site-Version"
};
const decodedTokenPayloadSchema = z.object({
  exp: z.number()
});
const siteVersionSchema = z.object({
  version: z.string(),
  token: z.string()
});
function millisecondsToSeconds(ms) {
  return Math.floor(ms / 1e3);
}
function serializeSiteVersion(data) {
  const jsonString = JSON.stringify({ version: data.version, token: data.token });
  return jsonString;
}
function parseSerializedSiteVersion(input) {
  try {
    return siteVersionSchema.parse(JSON.parse(input));
  } catch {
    console.error("Failed to parse serialized site version:", input);
    return null;
  }
}
function getSiteVersionTokenPayload(siteVersion) {
  try {
    const decoded = jwtDecode(siteVersion.token);
    return decodedTokenPayloadSchema.parse(decoded);
  } catch (error) {
    console.error("Invalid site version token");
    throw error;
  }
}
function secondsUntilTokenExpiration(tokenPayload) {
  const currentTime = millisecondsToSeconds(Date.now());
  return Math.max(tokenPayload.exp - currentTime, 0);
}
function secondsUntilSiteVersionExpiration(siteVersion) {
  try {
    const tokenPayload = getSiteVersionTokenPayload(siteVersion);
    return secondsUntilTokenExpiration(tokenPayload);
  } catch (error) {
    console.error("Failed to check site version expiration:", error);
    return 0;
  }
}
function isSiteVersionExpired(siteVersion) {
  return secondsUntilSiteVersionExpiration(siteVersion) <= 0;
}
function deserializeSiteVersion(input) {
  try {
    const parsedSiteVersion = parseSerializedSiteVersion(input);
    if (parsedSiteVersion == null)
      return null;
    if (isSiteVersionExpired(parsedSiteVersion)) {
      console.error("Site version token is expired");
      return null;
    }
    return parsedSiteVersion;
  } catch {
    console.error("Failed to deserialize site version:", input);
    return null;
  }
}
export {
  ApiHandlerHeaders,
  deserializeSiteVersion,
  secondsUntilSiteVersionExpiration,
  serializeSiteVersion,
  siteVersionSchema
};
//# sourceMappingURL=index.js.map