var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var apps_exports = {};
__export(apps_exports, {
  buildAppsApiClientMethods: () => buildAppsApiClientMethods
});
module.exports = __toCommonJS(apps_exports);
var import_request = require("../core/request.js");
function buildPublicAppPath(normalizeCreatorItemSlug, creatorUsername, appName, suffix = "") {
  const creator = normalizeCreatorItemSlug(creatorUsername, "creator");
  const name = normalizeCreatorItemSlug(appName, "name");
  return `/apps/${encodeURIComponent(creator)}/${encodeURIComponent(name)}${suffix}`;
}
function appendNormalizedTagParams(params, tags) {
  if (!Array.isArray(tags)) {
    return;
  }
  for (const tag of tags) {
    if (typeof tag !== "string") {
      continue;
    }
    const normalized = tag.trim();
    if (normalized.length > 0) {
      params.append("tag", normalized);
    }
  }
}
function appendAppCapabilityFilterParams(params, filters) {
  if (typeof filters.auth === "string" && filters.auth.trim().length > 0) {
    params.set("auth", filters.auth.trim());
  }
  if (typeof filters.controller === "string" && filters.controller.trim().length > 0) {
    params.set("controller", filters.controller.trim());
  }
  if (filters.controllerCompatible === true) {
    params.set("controllerCompatible", "1");
  }
  if (typeof filters.surface === "string" && filters.surface.trim().length > 0) {
    params.set("surface", filters.surface.trim());
  }
}
function appendFinitePaginationParam(params, key, value) {
  if (typeof value === "number" && Number.isFinite(value)) {
    params.set(key, String(value));
  }
}
async function buildAuthorizedHeaders(getClientHeaders, resolveToken) {
  const headers = new Headers();
  for (const [key, value] of Object.entries(getClientHeaders())) {
    headers.set(key, value);
  }
  const token = await resolveToken();
  if (token) {
    headers.set("authorization", `Bearer ${token}`);
  }
  return headers;
}
async function fetchAppsByCreatorRequest(request, handleApiError, creatorUsername, options = {}) {
  const normalizedCreator = creatorUsername.trim();
  const params = new URLSearchParams();
  if (typeof options.limit === "number" && Number.isFinite(options.limit)) {
    params.set("limit", String(options.limit));
  }
  if (typeof options.offset === "number" && Number.isFinite(options.offset)) {
    params.set("offset", String(options.offset));
  }
  if (typeof options.type === "string" && options.type.trim().length > 0) {
    params.set("type", options.type.trim());
  }
  if (typeof options.sort === "string" && options.sort.trim().length > 0) {
    params.set("sort", options.sort.trim());
  }
  appendAppCapabilityFilterParams(params, options);
  appendNormalizedTagParams(params, options.tags);
  const query = params.toString();
  const response = await request({
    method: "GET",
    path: `/creators/${encodeURIComponent(normalizedCreator)}/apps` + (query ? `?${query}` : "")
  });
  if (response.status !== 200) {
    handleApiError(response, "fetch_apps_by_creator");
  }
  return response.body;
}
async function buildAppUploadAuthorizedHeaders(input) {
  return await buildAuthorizedHeaders(input.getClientHeaders, input.resolveToken);
}
function buildAppsApiClientMethods(input) {
  const { request, handleApiError, fetchImpl, includeBrowserCredentials, resolveBaseUrl, resolveUrl, parseResponseBody, resolveToken, getClientHeaders, buildCreatorAppMutationPath, normalizeCreatorItemSlug, normalizeSemverInput, parseContentDispositionFilename } = input;
  return {
    async fetchApps(options = {}) {
      const params = new URLSearchParams();
      if (typeof options.limit === "number" && Number.isFinite(options.limit)) {
        params.set("limit", String(options.limit));
      }
      if (typeof options.offset === "number" && Number.isFinite(options.offset)) {
        params.set("offset", String(options.offset));
      }
      if (typeof options.sort === "string" && options.sort.trim().length > 0) {
        params.set("sort", options.sort.trim());
      }
      appendAppCapabilityFilterParams(params, options);
      appendNormalizedTagParams(params, options.tags);
      const query = params.toString();
      const response = await request({
        method: "GET",
        path: "/apps" + (query ? `?${query}` : "")
      });
      if (response.status !== 200) {
        handleApiError(response, "fetch_apps");
      }
      return response.body;
    },
    async fetchAppsByType(type, options = {}) {
      const params = new URLSearchParams();
      if (typeof options.limit === "number" && Number.isFinite(options.limit)) {
        params.set("limit", String(options.limit));
      }
      if (typeof options.offset === "number" && Number.isFinite(options.offset)) {
        params.set("offset", String(options.offset));
      }
      if (typeof options.sort === "string" && options.sort.trim().length > 0) {
        params.set("sort", options.sort.trim());
      }
      appendAppCapabilityFilterParams(params, options);
      appendNormalizedTagParams(params, options.tags);
      const query = params.toString();
      const response = await request({
        method: "GET",
        path: `/apps/types/${encodeURIComponent(type)}` + (query ? `?${query}` : "")
      });
      if (response.status !== 200) {
        handleApiError(response, "fetch_apps_by_type");
      }
      return response.body;
    },
    async fetchAppsByCreator(creatorUsername, options = {}) {
      return fetchAppsByCreatorRequest(request, handleApiError, creatorUsername, options);
    },
    async fetchAppBySlug(creatorUsername, appName, options = {}) {
      const params = new URLSearchParams();
      if (options.includeDependencies === true) {
        params.set("includeDependencies", "1");
      }
      const response = await request({
        method: "GET",
        path: `/apps/${encodeURIComponent(creatorUsername)}/${encodeURIComponent(appName)}${params.size > 0 ? `?${params.toString()}` : ""}`
      });
      if (response.status !== 200) {
        handleApiError(response, "fetch_app");
      }
      return response.body;
    },
    async fetchAppMoreCollections(creatorUsername, appName, options = {}) {
      const params = new URLSearchParams();
      appendFinitePaginationParam(params, "limit", options.limit);
      const response = await request({
        method: "GET",
        path: `${buildPublicAppPath(normalizeCreatorItemSlug, creatorUsername, appName, "/more")}${params.size > 0 ? `?${params.toString()}` : ""}`
      });
      if (response.status !== 200) {
        handleApiError(response, "fetch_app_more_collections");
      }
      return response.body;
    },
    async fetchAppMoreCollectionPage(creatorUsername, appName, collectionKey, options = {}) {
      const params = new URLSearchParams();
      appendFinitePaginationParam(params, "limit", options.limit);
      appendFinitePaginationParam(params, "offset", options.offset);
      const response = await request({
        method: "GET",
        path: `${buildPublicAppPath(normalizeCreatorItemSlug, creatorUsername, appName, `/more/${encodeURIComponent(collectionKey)}`)}${params.size > 0 ? `?${params.toString()}` : ""}`
      });
      if (response.status !== 200) {
        handleApiError(response, "fetch_app_more_collection_page");
      }
      return response.body;
    },
    async requestAppAccessToken(appId) {
      const response = await request({
        method: "POST",
        path: `/apps/${encodeURIComponent(String(appId))}/token`
      });
      if (response.status !== 200) {
        handleApiError(response, "request_app_access_token");
      }
      return response.body;
    },
    async sendAppLog(appId, entry) {
      const response = await request({
        method: "POST",
        path: `/apps/${encodeURIComponent(String(appId))}/logs`,
        body: entry
      });
      if (response.status !== 200) {
        handleApiError(response, "send_app_log");
      }
      return response.body;
    },
    async createApp(creatorUsername, createRequest) {
      const response = await request({
        method: "POST",
        path: buildCreatorAppMutationPath(creatorUsername),
        body: createRequest
      });
      if (response.status !== 200) {
        handleApiError(response, "create_app");
      }
      return response.body;
    },
    async updateApp(creatorUsername, name, updateRequest) {
      const response = await request({
        method: "PATCH",
        path: buildCreatorAppMutationPath(creatorUsername, name),
        body: updateRequest
      });
      if (response.status !== 200) {
        handleApiError(response, "update_app");
      }
      return response.body;
    },
    async initializeAppUpload(creatorUsername, appName, requestBody) {
      const response = await request({
        method: "POST",
        path: `${buildCreatorAppMutationPath(creatorUsername, appName)}/upload-sessions`,
        body: requestBody
      });
      if (response.status !== 200) {
        handleApiError(response, "initialize_app_upload");
      }
      return response.body;
    },
    async uploadAppSessionFile(creatorUsername, appName, sessionId, fileKey, options) {
      const form = new FormData();
      const filename = typeof options.filename === "string" && options.filename.trim().length > 0 ? options.filename.trim() : "upload.bin";
      form.append("file", options.file, filename);
      const base = resolveBaseUrl();
      const headers = await buildAppUploadAuthorizedHeaders({ getClientHeaders, resolveToken });
      const path = `${buildCreatorAppMutationPath(creatorUsername, appName)}/upload-sessions/${encodeURIComponent(sessionId)}/files/${encodeURIComponent(fileKey)}`;
      const response = await fetchImpl(resolveUrl(base, path), {
        method: "POST",
        headers,
        body: form,
        ...(0, import_request.buildBrowserCredentialsInit)(includeBrowserCredentials)
      });
      const parsed = await parseResponseBody(response);
      const apiResponse = { status: response.status, body: parsed, headers: response.headers };
      if (response.status !== 200) {
        handleApiError(apiResponse, "upload_app_session_file");
      }
      return parsed;
    },
    async uploadAppSessionOwnedAsset(creatorUsername, appName, sessionId, uploadKey, options) {
      const form = new FormData();
      for (const entry of options.files) {
        const fieldName = typeof entry.fieldName === "string" && entry.fieldName.trim().length > 0 ? entry.fieldName.trim() : "file";
        const filename = typeof entry.filename === "string" && entry.filename.trim().length > 0 ? entry.filename.trim() : "upload.bin";
        form.append(fieldName, entry.file, filename);
      }
      const base = resolveBaseUrl();
      const headers = await buildAppUploadAuthorizedHeaders({ getClientHeaders, resolveToken });
      const path = `${buildCreatorAppMutationPath(creatorUsername, appName)}/upload-sessions/${encodeURIComponent(sessionId)}/owned-assets/${encodeURIComponent(uploadKey)}`;
      const response = await fetchImpl(resolveUrl(base, path), {
        method: "POST",
        headers,
        body: form,
        ...(0, import_request.buildBrowserCredentialsInit)(includeBrowserCredentials)
      });
      const parsed = await parseResponseBody(response);
      const apiResponse = { status: response.status, body: parsed, headers: response.headers };
      if (response.status !== 200) {
        handleApiError(apiResponse, "upload_app_session_owned_asset");
      }
      return parsed;
    },
    async finalizeAppUpload(creatorUsername, appName, sessionId) {
      const response = await request({
        method: "POST",
        path: `${buildCreatorAppMutationPath(creatorUsername, appName)}/upload-sessions/${encodeURIComponent(sessionId)}/finalize`
      });
      if (response.status !== 200) {
        handleApiError(response, "finalize_app_upload");
      }
      return response.body;
    },
    async fetchAppUploadLaunchCheckPreview(creatorUsername, appName, sessionId) {
      const response = await request({
        method: "GET",
        path: `${buildCreatorAppMutationPath(creatorUsername, appName)}/upload-sessions/${encodeURIComponent(sessionId)}/launch-check/preview`
      });
      if (response.status !== 200) {
        handleApiError(response, "fetch_app_upload_launch_check_preview");
      }
      return response.body;
    },
    async recordAppUploadLaunchCheck(creatorUsername, appName, sessionId, requestBody) {
      const response = await request({
        method: "POST",
        path: `${buildCreatorAppMutationPath(creatorUsername, appName)}/upload-sessions/${encodeURIComponent(sessionId)}/launch-check`,
        body: requestBody
      });
      if (response.status !== 200) {
        handleApiError(response, "record_app_upload_launch_check");
      }
      return response.body;
    },
    async abortAppUpload(creatorUsername, appName, sessionId) {
      const response = await request({
        method: "POST",
        path: `${buildCreatorAppMutationPath(creatorUsername, appName)}/upload-sessions/${encodeURIComponent(sessionId)}/abort`
      });
      if (response.status !== 200) {
        handleApiError(response, "abort_app_upload");
      }
      return response.body;
    },
    async fetchAppRelated(creatorUsername, appName) {
      const response = await request({
        method: "GET",
        path: buildPublicAppPath(normalizeCreatorItemSlug, creatorUsername, appName, "/related")
      });
      if (response.status !== 200) {
        handleApiError(response, "get_app_related");
      }
      return response.body;
    },
    async requestDevAppAccessToken(appId, slot) {
      const response = await request({
        method: "POST",
        path: `/apps/${encodeURIComponent(String(appId))}/dev/players/${encodeURIComponent(String(slot))}/token`
      });
      if (response.status !== 200) {
        handleApiError(response, "request_dev_app_access_token");
      }
      return response.body;
    },
    async resetDevPlayer(appId, slot) {
      const response = await request({
        method: "POST",
        path: `/apps/${encodeURIComponent(String(appId))}/dev/players/${encodeURIComponent(String(slot))}/reset`
      });
      if (response.status !== 200) {
        handleApiError(response, "reset_dev_player");
      }
      return response.body;
    },
    async resetAllDevPlayers(appId) {
      const response = await request({
        method: "POST",
        path: `/apps/${encodeURIComponent(String(appId))}/dev/players/reset-all`
      });
      if (response.status !== 200) {
        handleApiError(response, "reset_all_dev_players");
      }
      return response.body;
    },
    async listAppVersions(creatorUsername, appName) {
      const path = `/apps/${encodeURIComponent(creatorUsername)}/${encodeURIComponent(appName)}/versions`;
      const response = await request({
        method: "GET",
        path
      });
      if (response.status !== 200) {
        handleApiError(response, "list_app_versions");
      }
      return response.body;
    },
    async getAppVersion(creatorUsername, appName, version) {
      const normalizedVersion = normalizeSemverInput(version);
      const path = `/apps/${encodeURIComponent(creatorUsername)}/${encodeURIComponent(appName)}/versions/${encodeURIComponent(normalizedVersion)}`;
      const response = await request({
        method: "GET",
        path
      });
      if (response.status !== 200) {
        handleApiError(response, "get_app_version");
      }
      return response.body;
    },
    async fetchAppRuntimeAssets(creatorUsername, appName, version) {
      const normalizedVersion = normalizeSemverInput(version);
      const path = `/apps/${encodeURIComponent(creatorUsername)}/${encodeURIComponent(appName)}/versions/${encodeURIComponent(normalizedVersion)}/runtime-assets`;
      const response = await request({
        method: "GET",
        path
      });
      if (response.status !== 200) {
        handleApiError(response, "fetch_app_runtime_assets");
      }
      return response.body;
    },
    async downloadAppSource(creatorUsername, appName, version) {
      const creator = normalizeCreatorItemSlug(creatorUsername, "creator");
      const name = normalizeCreatorItemSlug(appName, "name");
      const normalizedVersion = normalizeSemverInput(version);
      const path = `/apps/${encodeURIComponent(creator)}/${encodeURIComponent(name)}/versions/${encodeURIComponent(normalizedVersion)}/source`;
      const base = resolveBaseUrl();
      const headers = new Headers();
      for (const [key, value] of Object.entries(getClientHeaders())) {
        headers.set(key, value);
      }
      const token = await resolveToken();
      if (token) {
        headers.set("authorization", `Bearer ${token}`);
      }
      const response = await fetchImpl(resolveUrl(base, path), {
        method: "GET",
        headers,
        ...(0, import_request.buildBrowserCredentialsInit)(includeBrowserCredentials)
      });
      if (!response.ok) {
        const parsed = await parseResponseBody(response);
        handleApiError({ status: response.status, body: parsed, headers: response.headers }, "download_app_source");
      }
      const blob = await response.blob();
      const filename = parseContentDispositionFilename(response.headers.get("content-disposition")) ?? `${name}-${normalizedVersion}-source.zip`;
      const headerSize = response.headers.get("content-length");
      const parsedSize = headerSize ? Number.parseInt(headerSize, 10) : Number.NaN;
      const checksumHeader = response.headers.get("x-app-source-checksum");
      return {
        blob,
        metadata: {
          filename,
          sizeBytes: Number.isFinite(parsedSize) && parsedSize >= 0 ? parsedSize : blob.size,
          checksum: checksumHeader ?? null
        }
      };
    },
    async updateAppVersion(creatorUsername, appName, version, updates) {
      const path = `${buildCreatorAppMutationPath(creatorUsername, appName)}/versions/${encodeURIComponent(version)}`;
      const response = await request({
        method: "PATCH",
        path,
        body: updates
      });
      if (response.status !== 200) {
        handleApiError(response, "update_app_version");
      }
      return response.body;
    },
    async deleteAppVersion(creatorUsername, appName, version) {
      const path = `${buildCreatorAppMutationPath(creatorUsername, appName)}/versions/${encodeURIComponent(version)}`;
      const response = await request({
        method: "DELETE",
        path
      });
      if (response.status !== 200) {
        handleApiError(response, "delete_app_version");
      }
      return response.body;
    },
    async deleteApp(creatorUsername, name) {
      const response = await request({
        method: "DELETE",
        path: buildCreatorAppMutationPath(creatorUsername, name)
      });
      if (response.status !== 200) {
        handleApiError(response, "delete_app");
      }
      return response.body;
    },
    async fetchRemixScaffold(creatorUsername, appName, version) {
      const params = new URLSearchParams();
      if (typeof version === "string" && version.trim().length > 0) {
        params.set("version", version.trim());
      }
      const response = await request({
        method: "GET",
        path: `${buildPublicAppPath(normalizeCreatorItemSlug, creatorUsername, appName)}/remix${params.size > 0 ? `?${params.toString()}` : ""}`
      });
      if (response.status !== 200) {
        handleApiError(response, "fetch_remix_scaffold");
      }
      return response.body;
    }
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildAppsApiClientMethods
});
