'use strict';

var axios = require('axios');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var axios__default = /*#__PURE__*/_interopDefault(axios);

// src/adapters/index.ts

// src/core/adapter-registry.ts
var registry = {};
var localAdapter = (config) => {
  return {
    submit() {
    },
    async send() {
      var _a, _b;
      const result = { data: config.data };
      if ((_a = config.callbacks) == null ? void 0 : _a.onSuccess) {
        config.callbacks.onSuccess(result);
      }
      if ((_b = config.callbacks) == null ? void 0 : _b.onFinish) {
        config.callbacks.onFinish();
      }
      return result;
    },
    run() {
      this.submit();
    }
  };
};
registry.local = localAdapter;
function registerAdapter(key, factory) {
  registry[key] = factory;
}
function getAdapter(key) {
  const factory = registry[key];
  return factory;
}
function hasAdapter(key) {
  return typeof registry[key] === "function";
}
var createAxiosAdapter = (config) => {
  const { method, url, data, callbacks, errorBag } = config;
  function buildRequestConfig(options) {
    var _a;
    return {
      method,
      url,
      data,
      ...options,
      headers: {
        ...(_a = options == null ? void 0 : options.headers) != null ? _a : {},
        "X-Inertia-Error-Bag": errorBag
      }
    };
  }
  function submit(options) {
    let finished = false;
    const finish = () => {
      var _a;
      if (finished) return;
      finished = true;
      (_a = callbacks == null ? void 0 : callbacks.onFinish) == null ? void 0 : _a.call(callbacks);
    };
    axios__default.default.request(buildRequestConfig(options)).then((response) => {
      var _a;
      (_a = callbacks == null ? void 0 : callbacks.onSuccess) == null ? void 0 : _a.call(callbacks, response);
    }).catch((error) => {
      var _a, _b, _c;
      const axiosErr = error;
      const payload = (_b = (_a = axiosErr == null ? void 0 : axiosErr.response) == null ? void 0 : _a.data) != null ? _b : error;
      (_c = callbacks == null ? void 0 : callbacks.onError) == null ? void 0 : _c.call(callbacks, payload);
    }).finally(() => {
      finish();
    });
  }
  function send(options) {
    return new Promise((resolve, reject) => {
      let finished = false;
      const finish = () => {
        var _a;
        if (finished) return;
        finished = true;
        (_a = callbacks == null ? void 0 : callbacks.onFinish) == null ? void 0 : _a.call(callbacks);
      };
      axios__default.default.request(buildRequestConfig(options)).then((response) => {
        var _a;
        (_a = callbacks == null ? void 0 : callbacks.onSuccess) == null ? void 0 : _a.call(callbacks, response);
        resolve(response);
      }).catch((error) => {
        var _a, _b, _c;
        const axiosErr = error;
        const payload = (_b = (_a = axiosErr == null ? void 0 : axiosErr.response) == null ? void 0 : _a.data) != null ? _b : error;
        (_c = callbacks == null ? void 0 : callbacks.onError) == null ? void 0 : _c.call(callbacks, payload);
        reject(payload);
      }).finally(() => {
        finish();
      });
    });
  }
  function run(options) {
    return send(options);
  }
  return {
    submit,
    send,
    run
  };
};

// src/adapters/inertia.ts
async function loadInertiaRouter() {
  var _a;
  const mod = await import('@inertiajs/react');
  const router = (_a = mod == null ? void 0 : mod.router) != null ? _a : mod == null ? void 0 : mod.Inertia;
  if (!router || typeof router.visit !== "function") {
    throw new Error(
      "[form-palette] Inertia router not found in @inertiajs/react"
    );
  }
  return router;
}
function normalizeInertiaError(raw) {
  if (raw && typeof raw === "object" && "errors" in raw && typeof raw.errors === "object") {
    return raw;
  }
  if (raw && typeof raw === "object" && !("errors" in raw)) {
    return { errors: raw };
  }
  return raw;
}
var createInertiaAdapter = (config) => {
  const { method = "post", url, data, callbacks, errorBag } = config;
  const upperMethod = method.toUpperCase();
  function buildOptions(resolve, reject, extraOptions) {
    const user = extraOptions != null ? extraOptions : {};
    return {
      ...user,
      // user first
      errorBag,
      method: upperMethod,
      // @ts-ignore
      data,
      preserveState: "errors",
      onSuccess: (page) => {
        var _a, _b;
        (_a = user.onSuccess) == null ? void 0 : _a.call(user, page);
        (_b = callbacks == null ? void 0 : callbacks.onSuccess) == null ? void 0 : _b.call(callbacks, page);
        resolve == null ? void 0 : resolve(page);
      },
      onError: (rawErrors) => {
        var _a, _b;
        (_a = user.onError) == null ? void 0 : _a.call(user, rawErrors);
        const payload = normalizeInertiaError(rawErrors);
        (_b = callbacks == null ? void 0 : callbacks.onError) == null ? void 0 : _b.call(callbacks, payload);
        reject == null ? void 0 : reject(payload);
      },
      onFinish: (params) => {
        var _a, _b;
        (_a = user.onFinish) == null ? void 0 : _a.call(user, params);
        (_b = callbacks == null ? void 0 : callbacks.onFinish) == null ? void 0 : _b.call(callbacks);
      }
    };
  }
  function submit(options) {
    (async () => {
      var _a;
      let finished = false;
      const finish = () => {
        var _a2;
        if (finished) return;
        finished = true;
        (_a2 = callbacks == null ? void 0 : callbacks.onFinish) == null ? void 0 : _a2.call(callbacks);
      };
      try {
        const router = await loadInertiaRouter();
        const visitOptions = buildOptions(
          void 0,
          void 0,
          options
        );
        router.visit(url, visitOptions);
      } catch (error) {
        const payload = normalizeInertiaError(error);
        (_a = callbacks == null ? void 0 : callbacks.onError) == null ? void 0 : _a.call(callbacks, payload);
        finish();
      }
    })();
  }
  function send(options) {
    return new Promise(async (resolve, reject) => {
      var _a;
      let finished = false;
      const finish = () => {
        var _a2;
        if (finished) return;
        finished = true;
        (_a2 = callbacks == null ? void 0 : callbacks.onFinish) == null ? void 0 : _a2.call(callbacks);
      };
      try {
        const router = await loadInertiaRouter();
        const visitOptions = buildOptions(
          (page) => {
            resolve(page);
          },
          (err) => {
            reject(err);
          },
          options
        );
        router.visit(url, visitOptions);
      } catch (error) {
        const payload = normalizeInertiaError(error);
        (_a = callbacks == null ? void 0 : callbacks.onError) == null ? void 0 : _a.call(callbacks, payload);
        finish();
        reject(payload);
      }
    });
  }
  function run(options) {
    return send(options);
  }
  return {
    submit,
    send,
    run
  };
};

// src/adapters/index.ts
function registerAxiosAdapter() {
  if (!axios__default.default || typeof axios__default.default.request !== "function") {
    throw new Error(
      "[form-palette] Axios does not appear to be available. Make sure 'axios' is installed and resolvable before calling registerAxiosAdapter()."
    );
  }
  registerAdapter("axios", createAxiosAdapter);
}
async function registerInertiaAdapter() {
  var _a;
  try {
    const mod = await import('@inertiajs/react');
    const router = (_a = mod == null ? void 0 : mod.router) != null ? _a : mod == null ? void 0 : mod.Inertia;
    if (!router || typeof router.visit !== "function") {
      throw new Error(
        "[form-palette] '@inertiajs/react' was imported, but no router with a .visit() method was found."
      );
    }
  } catch (error) {
    throw new Error(
      "[form-palette] Failed to import '@inertiajs/react'. Cannot register the 'inertia' adapter. Make sure '@inertiajs/react' is installed and resolvable."
    );
  }
  registerAdapter("inertia", createInertiaAdapter);
}
async function registerKnownAdapter(key) {
  switch (key) {
    case "axios":
      registerAxiosAdapter();
      return;
    case "inertia":
      await registerInertiaAdapter();
      return;
    default:
      throw new Error(
        `[form-palette] registerKnownAdapter: adapter "${key}" is not handled here.`
      );
  }
}
function registerAllAdapters() {
  registerAxiosAdapter();
  registerInertiaAdapter();
}

exports.createAxiosAdapter = createAxiosAdapter;
exports.createInertiaAdapter = createInertiaAdapter;
exports.getAdapter = getAdapter;
exports.hasAdapter = hasAdapter;
exports.localAdapter = localAdapter;
exports.registerAdapter = registerAdapter;
exports.registerAllAdapters = registerAllAdapters;
exports.registerAxiosAdapter = registerAxiosAdapter;
exports.registerInertiaAdapter = registerInertiaAdapter;
exports.registerKnownAdapter = registerKnownAdapter;
//# sourceMappingURL=adapters.js.map
//# sourceMappingURL=adapters.js.map