"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }

var _chunkQNZPOA54cjs = require('./chunk-QNZPOA54.cjs');


var _chunkTZQFJ5GXcjs = require('./chunk-TZQFJ5GX.cjs');


var _chunkWWOAKRNGcjs = require('./chunk-WWOAKRNG.cjs');


var _chunk5WNEYQIIcjs = require('./chunk-5WNEYQII.cjs');


var _chunk4QCVVDTAcjs = require('./chunk-4QCVVDTA.cjs');


var _chunkZ5TVWG3Icjs = require('./chunk-Z5TVWG3I.cjs');


var _chunkJIUTCNTBcjs = require('./chunk-JIUTCNTB.cjs');


var _chunkHHMXS5NCcjs = require('./chunk-HHMXS5NC.cjs');


var _chunkCYS6QBW6cjs = require('./chunk-CYS6QBW6.cjs');


var _chunkGWKHOJGDcjs = require('./chunk-GWKHOJGD.cjs');


var _chunkQOAWSFXAcjs = require('./chunk-QOAWSFXA.cjs');


var _chunkBFUNXZRXcjs = require('./chunk-BFUNXZRX.cjs');


var _chunkWTMV77T2cjs = require('./chunk-WTMV77T2.cjs');


var _chunkN5NFJW7Ycjs = require('./chunk-N5NFJW7Y.cjs');


var _chunkJXJC6WEWcjs = require('./chunk-JXJC6WEW.cjs');


var _chunkWQBBB6BNcjs = require('./chunk-WQBBB6BN.cjs');


var _chunkNEVFKRDUcjs = require('./chunk-NEVFKRDU.cjs');


var _chunk4W22EIRFcjs = require('./chunk-4W22EIRF.cjs');


var _chunkYO4M3BZLcjs = require('./chunk-YO4M3BZL.cjs');


var _chunkJTFWOEZFcjs = require('./chunk-JTFWOEZF.cjs');


var _chunkMB6NKETAcjs = require('./chunk-MB6NKETA.cjs');


var _chunkG3VDRMOHcjs = require('./chunk-G3VDRMOH.cjs');


var _chunk77JS7NDMcjs = require('./chunk-77JS7NDM.cjs');


var _chunk4ZMLRFDXcjs = require('./chunk-4ZMLRFDX.cjs');


var _chunkM2SSGV7Kcjs = require('./chunk-M2SSGV7K.cjs');


var _chunkM56QQHVAcjs = require('./chunk-M56QQHVA.cjs');


var _chunkKEI3GHDYcjs = require('./chunk-KEI3GHDY.cjs');


var _chunkK2UZPY6Ucjs = require('./chunk-K2UZPY6U.cjs');


var _chunkANN2QTMYcjs = require('./chunk-ANN2QTMY.cjs');


var _chunkQA2OYK7Ncjs = require('./chunk-QA2OYK7N.cjs');


var _chunkTXDVGTQDcjs = require('./chunk-TXDVGTQD.cjs');


var _chunkBLNXQAMXcjs = require('./chunk-BLNXQAMX.cjs');


var _chunkG5FKTWUCcjs = require('./chunk-G5FKTWUC.cjs');


var _chunk5APJZUIHcjs = require('./chunk-5APJZUIH.cjs');


var _chunkBM6NCHPLcjs = require('./chunk-BM6NCHPL.cjs');


var _chunkYWDWPVICcjs = require('./chunk-YWDWPVIC.cjs');


var _chunkM2UDF7PYcjs = require('./chunk-M2UDF7PY.cjs');


var _chunkZL6KDJFTcjs = require('./chunk-ZL6KDJFT.cjs');


var _chunkIAHSYVYBcjs = require('./chunk-IAHSYVYB.cjs');


var _chunkEIIIKDOJcjs = require('./chunk-EIIIKDOJ.cjs');


var _chunkOXJOO2YFcjs = require('./chunk-OXJOO2YF.cjs');


var _chunkLKRBFBFNcjs = require('./chunk-LKRBFBFN.cjs');


var _chunkT67ZXTVGcjs = require('./chunk-T67ZXTVG.cjs');


var _chunkFARDEGPHcjs = require('./chunk-FARDEGPH.cjs');


var _chunkL66IX6GXcjs = require('./chunk-L66IX6GX.cjs');


var _chunkRUZRPIHWcjs = require('./chunk-RUZRPIHW.cjs');


var _chunkDVM27A7Ecjs = require('./chunk-DVM27A7E.cjs');







var _chunkMHXQX7FScjs = require('./chunk-MHXQX7FS.cjs');


var _chunkNJK5F5TFcjs = require('./chunk-NJK5F5TF.cjs');

// 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 && _optionalChain([response, 'access', _2 => _2.data, 'optionalAccess', _3 => _3[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 = _nullishCoalesce(config.maxRetries, () => ( DEFAULT_MAX_RETRIES));
  if (maxRetries <= 0) return;
  client.interceptors.response.use(void 0, async (error) => {
    if (_optionalChain([error, 'access', _4 => _4.response, 'optionalAccess', _5 => _5.status]) !== 429) throw error;
    const retryCountRaw = _optionalChain([error, 'access', _6 => _6.config, 'optionalAccess', _7 => _7.headers, 'optionalAccess', _8 => _8[RETRY_COUNT_HEADER]]);
    const retryCount = Number(_nullishCoalesce(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 : _nullishCoalesce(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 = _chunkMHXQX7FScjs.createApiClient.call(void 0, {
      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) => _chunkMHXQX7FScjs.expand.call(void 0, _nullishCoalesce(mod.default, () => ( mod)));
var registerBuiltinApis = (registry) => {
  registerApi({
    registry,
    name: "accessToken",
    loader: () => expandDef(_chunkOXJOO2YFcjs.require_access_token_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "address",
    loader: () => expandDef(_chunkT67ZXTVGcjs.require_address_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "addressSuggestions",
    loader: () => expandDef(_chunkLKRBFBFNcjs.require_address_suggestions_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "aiAgents",
    loader: () => expandDef(_chunkFARDEGPHcjs.require_ai_agents_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "app",
    loader: () => expandDef(_chunkL66IX6GXcjs.require_app_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "auditLogs",
    loader: () => expandDef(_chunkRUZRPIHWcjs.require_audit_logs_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "automation",
    loader: () => expandDef(_chunkDVM27A7Ecjs.require_automation_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "billing",
    loader: () => expandDef(_chunkG5FKTWUCcjs.require_billing_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "blueprintManifest",
    loader: () => expandDef(_chunk5APJZUIHcjs.require_blueprint_manifest_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "consent",
    loader: () => expandDef(_chunkBM6NCHPLcjs.require_consent_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "customerPortal",
    loader: () => expandDef(_chunkYWDWPVICcjs.require_customer_portal_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "dashboard",
    loader: () => expandDef(_chunkM2UDF7PYcjs.require_dashboard_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "dataGovernance",
    loader: () => expandDef(_chunkZL6KDJFTcjs.require_data_governance_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "deduplication",
    loader: () => expandDef(_chunkIAHSYVYBcjs.require_deduplication_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "design",
    loader: () => expandDef(_chunkEIIIKDOJcjs.require_design_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "document",
    loader: () => expandDef(_chunkM56QQHVAcjs.require_document_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "emailSettings",
    loader: () => expandDef(_chunkKEI3GHDYcjs.require_email_settings_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "emailTemplate",
    loader: () => expandDef(_chunkK2UZPY6Ucjs.require_email_template_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "entity",
    loader: () => expandDef(_chunkQA2OYK7Ncjs.require_entity_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "entityMapping",
    loader: () => expandDef(_chunkANN2QTMYcjs.require_entity_mapping_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "environments",
    loader: () => expandDef(_chunkTXDVGTQDcjs.require_environments_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "eventCatalog",
    loader: () => expandDef(_chunkBLNXQAMXcjs.require_event_catalog_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "file",
    loader: () => expandDef(_chunk4W22EIRFcjs.require_file_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "iban",
    loader: () => expandDef(_chunkYO4M3BZLcjs.require_iban_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "integrationToolkit",
    loader: () => expandDef(_chunkJTFWOEZFcjs.require_integration_toolkit_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "journey",
    loader: () => expandDef(_chunkMB6NKETAcjs.require_journey_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "kanban",
    loader: () => expandDef(_chunkG3VDRMOHcjs.require_kanban_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "message",
    loader: () => expandDef(_chunk77JS7NDMcjs.require_message_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "metering",
    loader: () => expandDef(_chunk4ZMLRFDXcjs.require_metering_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "notes",
    loader: () => expandDef(_chunkM2SSGV7Kcjs.require_notes_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "notification",
    loader: () => expandDef(_chunkGWKHOJGDcjs.require_notification_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "organization",
    loader: () => expandDef(_chunkQOAWSFXAcjs.require_organization_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "partnerDirectory",
    loader: () => expandDef(_chunkBFUNXZRXcjs.require_partner_directory_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "permissions",
    loader: () => expandDef(_chunkWTMV77T2cjs.require_permissions_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "pricing",
    loader: () => expandDef(_chunkJXJC6WEWcjs.require_pricing_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "pricingTier",
    loader: () => expandDef(_chunkN5NFJW7Ycjs.require_pricing_tier_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "purpose",
    loader: () => expandDef(_chunkWQBBB6BNcjs.require_purpose_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "sandbox",
    loader: () => expandDef(_chunkNEVFKRDUcjs.require_sandbox_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "sharing",
    loader: () => expandDef(_chunkTZQFJ5GXcjs.require_sharing_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "submission",
    loader: () => expandDef(_chunkWWOAKRNGcjs.require_submission_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "targeting",
    loader: () => expandDef(_chunk5WNEYQIIcjs.require_targeting_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "templateVariables",
    loader: () => expandDef(_chunk4QCVVDTAcjs.require_template_variables_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "user",
    loader: () => expandDef(_chunkZ5TVWG3Icjs.require_user_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "validationRules",
    loader: () => expandDef(_chunkJIUTCNTBcjs.require_validation_rules_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "webhooks",
    loader: () => expandDef(_chunkHHMXS5NCcjs.require_webhooks_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "workflow",
    loader: () => expandDef(_chunkQNZPOA54cjs.require_workflow_runtime.call(void 0, ))
  });
  registerApi({
    registry,
    name: "workflowDefinition",
    loader: () => expandDef(_chunkCYS6QBW6cjs.require_workflow_definition_runtime.call(void 0, ))
  });
};
var registerBuiltinExtensions = (extensions) => {
  let cached = null;
  extensions.set("journeyToolkit", {
    get value() {
      if (cached) return cached;
      try {
        cached = _chunkNJK5F5TFcjs.__require.call(void 0, "@epilot/epilot-journey-sdk");
      } catch (e) {
        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 = _chunkNJK5F5TFcjs.__require.call(void 0, "fs");
    const path = _chunkNJK5F5TFcjs.__require.call(void 0, "path");
    let dir = _nullishCoalesce(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 (e2) {
  }
};

// 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 _chunkMHXQX7FScjs.createApiHandle.call(void 0, {
      resolveClient: () => resolveClient({ registry, name, state }),
      createClient: () => _chunkMHXQX7FScjs.createApiClient.call(void 0, { 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) => _chunkMHXQX7FScjs.help.call(void 0, apiName);
        case "openapi":
          return (apiName) => _chunkMHXQX7FScjs.openapi.call(void 0, 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();








exports.applyLargeResponseInterceptor = applyLargeResponseInterceptor; exports.applyRetryInterceptor = applyRetryInterceptor; exports.authorize = _chunkMHXQX7FScjs.authorize; exports.createSDK = createSDK; exports.epilot = epilot; exports.help = _chunkMHXQX7FScjs.help; exports.openapi = _chunkMHXQX7FScjs.openapi;
