import {
  require_workflow_runtime
} from "./chunk-KQKBSWGI.js";
import {
  require_sharing_runtime
} from "./chunk-NPDSA7T2.js";
import {
  require_submission_runtime
} from "./chunk-IJR3GZKC.js";
import {
  require_targeting_runtime
} from "./chunk-BTTPWE2P.js";
import {
  require_template_variables_runtime
} from "./chunk-QTR3RH4N.js";
import {
  require_user_runtime
} from "./chunk-3XKBB5AE.js";
import {
  require_validation_rules_runtime
} from "./chunk-7IKQIVUS.js";
import {
  require_webhooks_runtime
} from "./chunk-A7AAVJGM.js";
import {
  require_workflow_definition_runtime
} from "./chunk-43GJY2EB.js";
import {
  require_notification_runtime
} from "./chunk-DZ3P537S.js";
import {
  require_organization_runtime
} from "./chunk-OEBV2PMV.js";
import {
  require_partner_directory_runtime
} from "./chunk-I2XRA5AM.js";
import {
  require_permissions_runtime
} from "./chunk-SITPUXIR.js";
import {
  require_pricing_tier_runtime
} from "./chunk-6VWCUZ5M.js";
import {
  require_pricing_runtime
} from "./chunk-MEUS7LCE.js";
import {
  require_purpose_runtime
} from "./chunk-D7Q4JGN7.js";
import {
  require_sandbox_runtime
} from "./chunk-UUVJYJHD.js";
import {
  require_file_runtime
} from "./chunk-E2WMGOM5.js";
import {
  require_iban_runtime
} from "./chunk-5MFHAXBT.js";
import {
  require_integration_toolkit_runtime
} from "./chunk-U4PUHKZC.js";
import {
  require_journey_runtime
} from "./chunk-VSZEOCIE.js";
import {
  require_kanban_runtime
} from "./chunk-IQOCHPWU.js";
import {
  require_message_runtime
} from "./chunk-DLYPVF4U.js";
import {
  require_metering_runtime
} from "./chunk-265TE2OV.js";
import {
  require_notes_runtime
} from "./chunk-RW5JOHG7.js";
import {
  require_document_runtime
} from "./chunk-75EI2Q64.js";
import {
  require_email_settings_runtime
} from "./chunk-EFWPEVXI.js";
import {
  require_email_template_runtime
} from "./chunk-JJWJLY42.js";
import {
  require_entity_mapping_runtime
} from "./chunk-SBSIGQDU.js";
import {
  require_entity_runtime
} from "./chunk-F7W62NKV.js";
import {
  require_environments_runtime
} from "./chunk-6OYECNL2.js";
import {
  require_event_catalog_runtime
} from "./chunk-TME4YJNP.js";
import {
  require_billing_runtime
} from "./chunk-CSK5ZUTS.js";
import {
  require_blueprint_manifest_runtime
} from "./chunk-VPDA5SAH.js";
import {
  require_consent_runtime
} from "./chunk-2BPBDRRO.js";
import {
  require_customer_portal_runtime
} from "./chunk-XT54462S.js";
import {
  require_dashboard_runtime
} from "./chunk-SZMCMLOQ.js";
import {
  require_data_governance_runtime
} from "./chunk-5ED7FB3Q.js";
import {
  require_deduplication_runtime
} from "./chunk-X2SC4GW5.js";
import {
  require_design_runtime
} from "./chunk-KIWRGUKM.js";
import {
  require_access_token_runtime
} from "./chunk-XSE4CFSM.js";
import {
  require_address_suggestions_runtime
} from "./chunk-4ZGZDE6D.js";
import {
  require_address_runtime
} from "./chunk-H45V55VT.js";
import {
  require_ai_agents_runtime
} from "./chunk-JENQHXFI.js";
import {
  require_app_runtime
} from "./chunk-LLZYRINH.js";
import {
  require_audit_logs_runtime
} from "./chunk-RELUU5QZ.js";
import {
  require_automation_runtime
} from "./chunk-WT26LFC2.js";
import {
  authorize,
  createApiClient,
  createApiHandle,
  expand,
  help,
  openapi
} from "./chunk-6AO46HG5.js";
import {
  __require
} from "./chunk-YPSWSI3M.js";

// src/large-response.ts
var CONTENT_TYPE = "application/large-response.vnd+json";
var REF_PROPERTY = "$payload_ref";
var applyLargeResponseInterceptor = (params) => {
  const { client, config } = params;
  if (config.enabled === false) return;
  client.interceptors.request.use((requestConfig) => {
    requestConfig.headers.Accept = CONTENT_TYPE;
    return requestConfig;
  });
  client.interceptors.response.use(async (response) => {
    const contentType = response.headers["content-type"];
    if (contentType === CONTENT_TYPE && response.data?.[REF_PROPERTY]) {
      const ref = response.data[REF_PROPERTY];
      const { data } = await client.get(ref, {
        transformResponse: (raw) => JSON.parse(raw)
      });
      response.data = data;
    }
    return response;
  });
};

// src/retry.ts
var DEFAULT_MAX_RETRIES = 3;
var DEFAULT_DELAY_MS = 1e3;
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
var RETRY_COUNT_HEADER = "x-epilot-sdk-retry-count";
var applyRetryInterceptor = (params) => {
  const { client, config } = params;
  const maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
  if (maxRetries <= 0) return;
  client.interceptors.response.use(void 0, async (error) => {
    if (error.response?.status !== 429) throw error;
    const retryCountRaw = error.config?.headers?.[RETRY_COUNT_HEADER];
    const retryCount = Number(retryCountRaw ?? 0);
    if (retryCount >= maxRetries) throw error;
    const retryAfterHeader = error.response.headers["retry-after"];
    const retryAfterSeconds = retryAfterHeader ? Number(retryAfterHeader) : NaN;
    const delayMs = Number.isFinite(retryAfterSeconds) ? retryAfterSeconds * 1e3 : config.defaultDelayMs ?? DEFAULT_DELAY_MS;
    await sleep(delayMs);
    const retryConfig = { ...error.config };
    retryConfig.headers.set(RETRY_COUNT_HEADER, String(retryCount + 1));
    return client.request(retryConfig);
  });
};

// src/registry.ts
var createRegistry = () => /* @__PURE__ */ new Map();
var registerApi = (params) => {
  const { registry, name, loader } = params;
  registry.set(name, { loader, instance: null });
};
var resolveClient = (params) => {
  const { registry, name, state } = params;
  const entry = registry.get(name);
  if (!entry) {
    const available = [...registry.keys()].join(", ");
    throw new Error(`Unknown API: "${name}". Available: ${available}`);
  }
  if (!entry.instance) {
    const definition = entry.loader();
    entry.instance = createApiClient({
      definition,
      token: state.token,
      headers: state.globalHeaders,
      apiName: name
    });
    applyLargeResponseInterceptor({ client: entry.instance, config: state.largeResponse });
    applyRetryInterceptor({ client: entry.instance, config: state.retry });
    if (state.tokenFn) {
      const tokenFn = state.tokenFn;
      entry.instance.interceptors.request.use(async (config) => {
        const resolved = await tokenFn();
        config.headers.authorization = `Bearer ${resolved}`;
        return config;
      });
    }
    for (const interceptor of state.interceptors) {
      if (interceptor.type === "request") {
        entry.instance.interceptors.request.use(interceptor.fulfilled, interceptor.rejected);
      } else {
        entry.instance.interceptors.response.use(interceptor.fulfilled, interceptor.rejected);
      }
    }
  }
  return entry.instance;
};
var resetAllClients = (registry) => {
  for (const entry of registry.values()) {
    entry.instance = null;
  }
};

// src/apis/_registry.ts
var expandDef = (mod) => expand(mod.default ?? mod);
var registerBuiltinApis = (registry) => {
  registerApi({
    registry,
    name: "accessToken",
    loader: () => expandDef(require_access_token_runtime())
  });
  registerApi({
    registry,
    name: "address",
    loader: () => expandDef(require_address_runtime())
  });
  registerApi({
    registry,
    name: "addressSuggestions",
    loader: () => expandDef(require_address_suggestions_runtime())
  });
  registerApi({
    registry,
    name: "aiAgents",
    loader: () => expandDef(require_ai_agents_runtime())
  });
  registerApi({
    registry,
    name: "app",
    loader: () => expandDef(require_app_runtime())
  });
  registerApi({
    registry,
    name: "auditLogs",
    loader: () => expandDef(require_audit_logs_runtime())
  });
  registerApi({
    registry,
    name: "automation",
    loader: () => expandDef(require_automation_runtime())
  });
  registerApi({
    registry,
    name: "billing",
    loader: () => expandDef(require_billing_runtime())
  });
  registerApi({
    registry,
    name: "blueprintManifest",
    loader: () => expandDef(require_blueprint_manifest_runtime())
  });
  registerApi({
    registry,
    name: "consent",
    loader: () => expandDef(require_consent_runtime())
  });
  registerApi({
    registry,
    name: "customerPortal",
    loader: () => expandDef(require_customer_portal_runtime())
  });
  registerApi({
    registry,
    name: "dashboard",
    loader: () => expandDef(require_dashboard_runtime())
  });
  registerApi({
    registry,
    name: "dataGovernance",
    loader: () => expandDef(require_data_governance_runtime())
  });
  registerApi({
    registry,
    name: "deduplication",
    loader: () => expandDef(require_deduplication_runtime())
  });
  registerApi({
    registry,
    name: "design",
    loader: () => expandDef(require_design_runtime())
  });
  registerApi({
    registry,
    name: "document",
    loader: () => expandDef(require_document_runtime())
  });
  registerApi({
    registry,
    name: "emailSettings",
    loader: () => expandDef(require_email_settings_runtime())
  });
  registerApi({
    registry,
    name: "emailTemplate",
    loader: () => expandDef(require_email_template_runtime())
  });
  registerApi({
    registry,
    name: "entity",
    loader: () => expandDef(require_entity_runtime())
  });
  registerApi({
    registry,
    name: "entityMapping",
    loader: () => expandDef(require_entity_mapping_runtime())
  });
  registerApi({
    registry,
    name: "environments",
    loader: () => expandDef(require_environments_runtime())
  });
  registerApi({
    registry,
    name: "eventCatalog",
    loader: () => expandDef(require_event_catalog_runtime())
  });
  registerApi({
    registry,
    name: "file",
    loader: () => expandDef(require_file_runtime())
  });
  registerApi({
    registry,
    name: "iban",
    loader: () => expandDef(require_iban_runtime())
  });
  registerApi({
    registry,
    name: "integrationToolkit",
    loader: () => expandDef(require_integration_toolkit_runtime())
  });
  registerApi({
    registry,
    name: "journey",
    loader: () => expandDef(require_journey_runtime())
  });
  registerApi({
    registry,
    name: "kanban",
    loader: () => expandDef(require_kanban_runtime())
  });
  registerApi({
    registry,
    name: "message",
    loader: () => expandDef(require_message_runtime())
  });
  registerApi({
    registry,
    name: "metering",
    loader: () => expandDef(require_metering_runtime())
  });
  registerApi({
    registry,
    name: "notes",
    loader: () => expandDef(require_notes_runtime())
  });
  registerApi({
    registry,
    name: "notification",
    loader: () => expandDef(require_notification_runtime())
  });
  registerApi({
    registry,
    name: "organization",
    loader: () => expandDef(require_organization_runtime())
  });
  registerApi({
    registry,
    name: "partnerDirectory",
    loader: () => expandDef(require_partner_directory_runtime())
  });
  registerApi({
    registry,
    name: "permissions",
    loader: () => expandDef(require_permissions_runtime())
  });
  registerApi({
    registry,
    name: "pricing",
    loader: () => expandDef(require_pricing_runtime())
  });
  registerApi({
    registry,
    name: "pricingTier",
    loader: () => expandDef(require_pricing_tier_runtime())
  });
  registerApi({
    registry,
    name: "purpose",
    loader: () => expandDef(require_purpose_runtime())
  });
  registerApi({
    registry,
    name: "sandbox",
    loader: () => expandDef(require_sandbox_runtime())
  });
  registerApi({
    registry,
    name: "sharing",
    loader: () => expandDef(require_sharing_runtime())
  });
  registerApi({
    registry,
    name: "submission",
    loader: () => expandDef(require_submission_runtime())
  });
  registerApi({
    registry,
    name: "targeting",
    loader: () => expandDef(require_targeting_runtime())
  });
  registerApi({
    registry,
    name: "templateVariables",
    loader: () => expandDef(require_template_variables_runtime())
  });
  registerApi({
    registry,
    name: "user",
    loader: () => expandDef(require_user_runtime())
  });
  registerApi({
    registry,
    name: "validationRules",
    loader: () => expandDef(require_validation_rules_runtime())
  });
  registerApi({
    registry,
    name: "webhooks",
    loader: () => expandDef(require_webhooks_runtime())
  });
  registerApi({
    registry,
    name: "workflow",
    loader: () => expandDef(require_workflow_runtime())
  });
  registerApi({
    registry,
    name: "workflowDefinition",
    loader: () => expandDef(require_workflow_definition_runtime())
  });
};
var registerBuiltinExtensions = (extensions) => {
  let cached = null;
  extensions.set("journeyToolkit", {
    get value() {
      if (cached) return cached;
      try {
        cached = __require("@epilot/epilot-journey-sdk");
      } catch {
        cached = void 0;
      }
      return cached;
    }
  });
};

// src/overrides.ts
var OVERRIDES_PATH = ".epilot/sdk-overrides.json";
var _loaded = false;
var createSpecLoader = (specPath, baseDir, fsModule, pathModule) => {
  let cached = null;
  return () => {
    if (cached) return cached;
    const absolutePath = pathModule.resolve(baseDir, specPath);
    const content = fsModule.readFileSync(absolutePath, "utf-8");
    cached = JSON.parse(content);
    return cached;
  };
};
var loadOverrides = (registry, cwd) => {
  if (_loaded) return;
  _loaded = true;
  try {
    if (typeof process === "undefined" || typeof process.cwd !== "function") return;
    const fs = __require("fs");
    const path = __require("path");
    let dir = cwd ?? process.cwd();
    let overridesFile = null;
    while (true) {
      const candidate = path.resolve(dir, OVERRIDES_PATH);
      if (fs.existsSync(candidate)) {
        overridesFile = candidate;
        break;
      }
      const parent = path.dirname(dir);
      if (parent === dir) break;
      dir = parent;
    }
    if (!overridesFile) return;
    const baseDir = path.dirname(overridesFile);
    const overrides = JSON.parse(fs.readFileSync(overridesFile, "utf-8"));
    for (const [name, specPath] of Object.entries(overrides)) {
      const loader = createSpecLoader(specPath, baseDir, fs, path);
      const existing = registry.get(name);
      if (existing) {
        existing.loader = loader;
        existing.instance = null;
      } else {
        registerApi({ registry, name, loader });
      }
    }
  } catch {
  }
};

// src/sdk.ts
var createSDK = () => {
  const registry = createRegistry();
  const extensions = /* @__PURE__ */ new Map();
  const state = {
    token: null,
    tokenFn: null,
    globalHeaders: {},
    interceptors: [],
    retry: { maxRetries: 3 },
    largeResponse: { enabled: true }
  };
  registerBuiltinApis(registry);
  registerBuiltinExtensions(extensions);
  loadOverrides(registry);
  const getHandle = (name) => {
    const entry = registry.get(name);
    if (!entry) {
      const available = [...registry.keys()].join(", ");
      throw new Error(`Unknown API: "${name}". Available: ${available}`);
    }
    return createApiHandle({
      resolveClient: () => resolveClient({ registry, name, state }),
      createClient: () => createApiClient({ definition: entry.loader(), apiName: name }),
      apiName: name
    });
  };
  const sdk = new Proxy({}, {
    get(_, prop) {
      if (typeof prop === "symbol") return void 0;
      switch (prop) {
        case "authorize":
          return (token) => {
            if (typeof token === "string") {
              state.token = token;
              state.tokenFn = null;
            } else {
              state.token = null;
              state.tokenFn = token;
            }
            resetAllClients(registry);
          };
        case "headers":
          return (headers) => {
            Object.assign(state.globalHeaders, headers);
            resetAllClients(registry);
          };
        case "retry":
          return (config) => {
            Object.assign(state.retry, config);
            resetAllClients(registry);
          };
        case "largeResponse":
          return (config) => {
            Object.assign(state.largeResponse, config);
            resetAllClients(registry);
          };
        case "interceptors": {
          const interceptorUse = {
            request: (fulfilled, rejected) => {
              state.interceptors.push({ type: "request", fulfilled, rejected });
              resetAllClients(registry);
            },
            response: (fulfilled, rejected) => {
              state.interceptors.push({ type: "response", fulfilled, rejected });
              resetAllClients(registry);
            }
          };
          return interceptorUse;
        }
        case "help":
          return (apiName) => help(apiName);
        case "openapi":
          return (apiName) => openapi(apiName);
        case "then":
        case "catch":
        case "finally":
        case "toJSON":
          return void 0;
        default:
          if (registry.has(prop)) {
            return getHandle(prop);
          }
          if (extensions.has(prop)) {
            return extensions.get(prop).value;
          }
          return void 0;
      }
    }
  });
  return sdk;
};

// src/index.ts
var epilot = createSDK();
export {
  applyLargeResponseInterceptor,
  applyRetryInterceptor,
  authorize,
  createSDK,
  epilot,
  help,
  openapi
};
