import "./chunk-DC5AMYBS.js";

// node_modules/js-cookie/dist/js.cookie.mjs
function assign(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      target[key] = source[key];
    }
  }
  return target;
}
var defaultConverter = {
  read: function(value) {
    if (value[0] === '"') {
      value = value.slice(1, -1);
    }
    return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
  },
  write: function(value) {
    return encodeURIComponent(value).replace(
      /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
      decodeURIComponent
    );
  }
};
function init(converter, defaultAttributes) {
  function set(name, value, attributes) {
    if (typeof document === "undefined") {
      return;
    }
    attributes = assign({}, defaultAttributes, attributes);
    if (typeof attributes.expires === "number") {
      attributes.expires = new Date(Date.now() + attributes.expires * 864e5);
    }
    if (attributes.expires) {
      attributes.expires = attributes.expires.toUTCString();
    }
    name = encodeURIComponent(name).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
    var stringifiedAttributes = "";
    for (var attributeName in attributes) {
      if (!attributes[attributeName]) {
        continue;
      }
      stringifiedAttributes += "; " + attributeName;
      if (attributes[attributeName] === true) {
        continue;
      }
      stringifiedAttributes += "=" + attributes[attributeName].split(";")[0];
    }
    return document.cookie = name + "=" + converter.write(value, name) + stringifiedAttributes;
  }
  function get(name) {
    if (typeof document === "undefined" || arguments.length && !name) {
      return;
    }
    var cookies = document.cookie ? document.cookie.split("; ") : [];
    var jar = {};
    for (var i = 0; i < cookies.length; i++) {
      var parts = cookies[i].split("=");
      var value = parts.slice(1).join("=");
      try {
        var found = decodeURIComponent(parts[0]);
        jar[found] = converter.read(value, found);
        if (name === found) {
          break;
        }
      } catch (e) {
      }
    }
    return name ? jar[name] : jar;
  }
  return Object.create(
    {
      set,
      get,
      remove: function(name, attributes) {
        set(
          name,
          "",
          assign({}, attributes, {
            expires: -1
          })
        );
      },
      withAttributes: function(attributes) {
        return init(this.converter, assign({}, this.attributes, attributes));
      },
      withConverter: function(converter2) {
        return init(assign({}, this.converter, converter2), this.attributes);
      }
    },
    {
      attributes: { value: Object.freeze(defaultAttributes) },
      converter: { value: Object.freeze(converter) }
    }
  );
}
var api = init(defaultConverter, { path: "/" });

// node_modules/@abi-software/sparc-annotation/dist/annotationService.js
var __classPrivateFieldSet = function(receiver, state, value, kind, f) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet = function(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _AnnotationService_instances;
var _AnnotationService_serverEndpoint;
var _AnnotationService_currentUser;
var _AnnotationService_currentError;
var _AnnotationService_request;
var SERVER_TIMEOUT = 1e4;
var AnnotationService = class {
  /**
   * @param  serverEndpoint  The URL of a map annotation service.
   */
  constructor(serverEndpoint) {
    _AnnotationService_instances.add(this);
    _AnnotationService_serverEndpoint.set(this, void 0);
    _AnnotationService_currentUser.set(this, null);
    _AnnotationService_currentError.set(
      this,
      null
      /**
       * @param  serverEndpoint  The URL of a map annotation service.
       */
    );
    if (serverEndpoint.slice(-1) === "/") {
      __classPrivateFieldSet(this, _AnnotationService_serverEndpoint, serverEndpoint.slice(0, -1), "f");
    } else {
      __classPrivateFieldSet(this, _AnnotationService_serverEndpoint, serverEndpoint, "f");
    }
  }
  /**
   * Get information about the logged-in SPARC user.
   *
   * Requires {@linkcode authenticate} to first be called.
   */
  get currentUser() {
    return __classPrivateFieldGet(this, _AnnotationService_currentUser, "f");
  }
  /**
   * Get information about any error from the last call
   * to {@linkcode authenticate}.
   */
  get currentError() {
    return __classPrivateFieldGet(this, _AnnotationService_currentError, "f");
  }
  /**
   * Authenticate the logged-in SPARC user.
   *
   * @param  userApiKey  The Api token of the logged-in Pennsieve user
   * @return  A Promise resolving to either data about a valid user
   *          or a reason why the user is invalid.
   */
  async authenticate(userApiKey) {
    __classPrivateFieldSet(this, _AnnotationService_currentError, null, "f");
    __classPrivateFieldSet(this, _AnnotationService_currentUser, null, "f");
    const userData = await __classPrivateFieldGet(this, _AnnotationService_instances, "m", _AnnotationService_request).call(this, userApiKey, "authenticate");
    if (!("error" in userData)) {
      api.set("annotation-key", userData.session, { secure: true, expires: 1 });
      __classPrivateFieldSet(this, _AnnotationService_currentUser, userData.data, "f");
      return Promise.resolve(__classPrivateFieldGet(this, _AnnotationService_currentUser, "f"));
    }
    api.remove("annotation-key");
    return Promise.resolve(__classPrivateFieldGet(this, _AnnotationService_currentError, "f"));
  }
  /**
   * Unauthenticate with the annotation service.
   *
   * @param  userApiKey  The Api token of the logged-in Pennsieve user
   * @return A Promise with data about the call.
   */
  async unauthenticate(userApiKey) {
    __classPrivateFieldSet(this, _AnnotationService_currentError, null, "f");
    __classPrivateFieldSet(this, _AnnotationService_currentUser, null, "f");
    const responseData = await __classPrivateFieldGet(this, _AnnotationService_instances, "m", _AnnotationService_request).call(this, userApiKey, "unauthenticate");
    if ("success" in responseData) {
      return Promise.resolve(responseData);
    }
    return Promise.resolve(__classPrivateFieldGet(this, _AnnotationService_currentError, "f"));
  }
  /**
   * Get identifiers of all annotated items in a resource.
   *
   * @param  userApiKey    The Api token of the logged-in Pennsieve user
   * @param  resourceId    The resource's identifier
   * @param  userId        A user identifier (ORCID). Optional
   * @param  participated  Get items the user was involved in annotating or not.
   *                       Optional, default ``true``
   * @return A Promise resolving to either a list of identifiers of annotated
   *         items or a reason why identifiers couldn't be retrieved.
   */
  async annotatedItemIds(userApiKey, resourceId, userId, participated) {
    const params = {
      resource: resourceId
    };
    if (userId !== void 0) {
      params.user = userId;
    }
    if (participated !== void 0) {
      params.participated = participated;
    }
    const itemIds = await __classPrivateFieldGet(this, _AnnotationService_instances, "m", _AnnotationService_request).call(this, userApiKey, "items/", "GET", params);
    if (!("error" in itemIds)) {
      return Promise.resolve(itemIds);
    }
    return Promise.resolve(__classPrivateFieldGet(this, _AnnotationService_currentError, "f"));
  }
  /**
   * Get all annotated features drawn on a resource.
   *
   * @param  userApiKey  The Api token of the logged-in Pennsieve user
   * @param  resourceId  The resource's identifier
   * @return             A Promise resolving to either a list of annotated
   *                     features drawn on the resource or a reason why
   *                     features couldn't be retrieved.
   */
  async drawnFeatures(userApiKey, resourceId, itemIds) {
    const params = {
      resource: resourceId
    };
    if (itemIds !== void 0) {
      params.items = itemIds;
    }
    const features = await __classPrivateFieldGet(this, _AnnotationService_instances, "m", _AnnotationService_request).call(this, userApiKey, "features/", "GET", params);
    if (!("error" in features)) {
      return Promise.resolve(features);
    }
    return Promise.resolve(__classPrivateFieldGet(this, _AnnotationService_currentError, "f"));
  }
  /**
   * Get all annotations about a specific item in a resource.
   *
   * @param  userApiKey  The Api token of the logged-in Pennsieve user
   * @param  resourceId  The resource's identifier
   * @param  itemId      The item's identifier within the resource
   * @return             A Promise resolving to either a list of
   *                     annotations about the item or a reason
   *                     why annotations couldn't be retrieved.
   */
  async itemAnnotations(userApiKey, resourceId, ItemId) {
    const annotations = await __classPrivateFieldGet(this, _AnnotationService_instances, "m", _AnnotationService_request).call(this, userApiKey, "annotations/", "GET", {
      resource: resourceId,
      item: ItemId
    });
    if (!("error" in annotations)) {
      return Promise.resolve(annotations);
    }
    return Promise.resolve(__classPrivateFieldGet(this, _AnnotationService_currentError, "f"));
  }
  /**
   * Get details of a specific annotation.
   *
   * @param  userApiKey  The Api token of the logged-in Pennsieve user
   * @param  annotationId  The annotation's URI
   * @return               A Promise resolving to either an annotation
   *                       with the given URI or a reason why the
   *                       annotation couldn't be retrieved.
   */
  async annotation(userApiKey, annotationId) {
    const annotation = await __classPrivateFieldGet(this, _AnnotationService_instances, "m", _AnnotationService_request).call(this, userApiKey, "annotation/", "GET", {
      annotation: annotationId
    });
    if (!("error" in annotation)) {
      return Promise.resolve(annotation);
    }
    return Promise.resolve(__classPrivateFieldGet(this, _AnnotationService_currentError, "f"));
  }
  /**
   * Add an annotation about a specific item in a resource.
   *
   * @param  userApiKey  The Api token of the logged-in Pennsieve user
   * @param   annotation  Annotation about the feature
   * @return              A Promise resolving to either the resulting
   *                      full annotation or a reason why the
   *                      annotation couldn't be added
   */
  async addAnnotation(userApiKey, userAnnotation) {
    if (__classPrivateFieldGet(this, _AnnotationService_currentUser, "f") && __classPrivateFieldGet(this, _AnnotationService_currentUser, "f").canUpdate) {
      const annotationRequest = Object.assign({
        creator: __classPrivateFieldGet(this, _AnnotationService_currentUser, "f"),
        created: (/* @__PURE__ */ new Date()).toISOString()
      }, userAnnotation);
      const annotationResponse = await __classPrivateFieldGet(this, _AnnotationService_instances, "m", _AnnotationService_request).call(this, userApiKey, `annotation/`, "POST", {
        data: annotationRequest
      });
      if (!("error" in annotationResponse)) {
        return Promise.resolve(annotationResponse);
      }
      __classPrivateFieldSet(this, _AnnotationService_currentError, annotationResponse, "f");
    } else {
      __classPrivateFieldSet(this, _AnnotationService_currentError, { error: "user cannot add annotation" }, "f");
    }
    return Promise.resolve(__classPrivateFieldGet(this, _AnnotationService_currentError, "f"));
  }
};
_AnnotationService_serverEndpoint = /* @__PURE__ */ new WeakMap(), _AnnotationService_currentUser = /* @__PURE__ */ new WeakMap(), _AnnotationService_currentError = /* @__PURE__ */ new WeakMap(), _AnnotationService_instances = /* @__PURE__ */ new WeakSet(), _AnnotationService_request = async function _AnnotationService_request2(userApiKey, endpoint, method = "GET", parameters = {}) {
  let noResponse = true;
  const abortController = new AbortController();
  setTimeout(() => {
    if (noResponse) {
      console.log("Annotation server timeout...");
      abortController.abort();
    }
  }, SERVER_TIMEOUT);
  const options = {
    method,
    signal: abortController.signal
  };
  let url = `${__classPrivateFieldGet(this, _AnnotationService_serverEndpoint, "f")}/${endpoint}`;
  const sessionKey = api.get("annotation-key") || "";
  if (method === "GET") {
    const params = [];
    for (const [key, value] of Object.entries(parameters)) {
      params.push(`${key}=${encodeURIComponent(JSON.stringify(value))}`);
    }
    params.push(`key=${encodeURIComponent(userApiKey)}`);
    params.push(`session=${encodeURIComponent(sessionKey)}`);
    url += "?" + params.join("&");
    options["headers"] = {
      "Accept": "application/json; charset=utf-8",
      "Cache-Control": "no-store"
    };
  } else if (method === "POST") {
    const params = Object.assign({
      key: userApiKey,
      session: sessionKey
    }, parameters);
    options["body"] = JSON.stringify(params);
    options["headers"] = {
      "Accept": "application/json; charset=utf-8",
      "Content-Type": "application/json; charset=utf-8",
      "Cache-Control": "no-store"
    };
  }
  const response = await fetch(url, options);
  noResponse = false;
  if (response.ok) {
    return Promise.resolve(await response.json());
  } else {
    __classPrivateFieldSet(this, _AnnotationService_currentError, { error: `${response.status} ${response.statusText}` }, "f");
    return Promise.resolve(__classPrivateFieldGet(this, _AnnotationService_currentError, "f"));
  }
};
export {
  AnnotationService
};
/*! Bundled license information:

js-cookie/dist/js.cookie.mjs:
  (*! js-cookie v3.0.5 | MIT *)
*/
//# sourceMappingURL=@abi-software_sparc-annotation.js.map