//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function() {
	return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
	if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
		key = keys[i];
		if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
			get: ((k) => from[k]).bind(null, key),
			enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
		});
	}
	return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
	value: mod,
	enumerable: true
}) : target, mod));

//#endregion
let node_crypto = require("node:crypto");
node_crypto = __toESM(node_crypto);

//#region ../../node_modules/oauth-1.0a/oauth-1.0a.js
var require_oauth_1_0a = /* @__PURE__ */ __commonJS({ "../../node_modules/oauth-1.0a/oauth-1.0a.js": ((exports, module) => {
	if (typeof module !== "undefined" && typeof exports !== "undefined") module.exports = OAuth$1;
	/**
	* Constructor
	* @param {Object} opts consumer key and secret
	*/
	function OAuth$1(opts) {
		if (!(this instanceof OAuth$1)) return new OAuth$1(opts);
		if (!opts) opts = {};
		if (!opts.consumer) throw new Error("consumer option is required");
		this.consumer = opts.consumer;
		this.nonce_length = opts.nonce_length || 32;
		this.version = opts.version || "1.0";
		this.parameter_seperator = opts.parameter_seperator || ", ";
		this.realm = opts.realm;
		if (typeof opts.last_ampersand === "undefined") this.last_ampersand = true;
		else this.last_ampersand = opts.last_ampersand;
		this.signature_method = opts.signature_method || "PLAINTEXT";
		if (this.signature_method == "PLAINTEXT" && !opts.hash_function) opts.hash_function = function(base_string, key) {
			return key;
		};
		if (!opts.hash_function) throw new Error("hash_function option is required");
		this.hash_function = opts.hash_function;
		this.body_hash_function = opts.body_hash_function || this.hash_function;
	}
	/**
	* OAuth request authorize
	* @param  {Object} request data
	* {
	*     method,
	*     url,
	*     data
	* }
	* @param  {Object} key and secret token
	* @return {Object} OAuth Authorized data
	*/
	OAuth$1.prototype.authorize = function(request, token) {
		var oauth_data = {
			oauth_consumer_key: this.consumer.key,
			oauth_nonce: this.getNonce(),
			oauth_signature_method: this.signature_method,
			oauth_timestamp: this.getTimeStamp(),
			oauth_version: this.version
		};
		if (!token) token = {};
		if (token.key !== void 0) oauth_data.oauth_token = token.key;
		if (!request.data) request.data = {};
		if (request.includeBodyHash) oauth_data.oauth_body_hash = this.getBodyHash(request, token.secret);
		oauth_data.oauth_signature = this.getSignature(request, token.secret, oauth_data);
		return oauth_data;
	};
	/**
	* Create a OAuth Signature
	* @param  {Object} request data
	* @param  {Object} token_secret key and secret token
	* @param  {Object} oauth_data   OAuth data
	* @return {String} Signature
	*/
	OAuth$1.prototype.getSignature = function(request, token_secret, oauth_data) {
		return this.hash_function(this.getBaseString(request, oauth_data), this.getSigningKey(token_secret));
	};
	/**
	* Create a OAuth Body Hash
	* @param {Object} request data
	*/
	OAuth$1.prototype.getBodyHash = function(request, token_secret) {
		var body = typeof request.data === "string" ? request.data : JSON.stringify(request.data);
		if (!this.body_hash_function) throw new Error("body_hash_function option is required");
		return this.body_hash_function(body, this.getSigningKey(token_secret));
	};
	/**
	* Base String = Method + Base Url + ParameterString
	* @param  {Object} request data
	* @param  {Object} OAuth data
	* @return {String} Base String
	*/
	OAuth$1.prototype.getBaseString = function(request, oauth_data) {
		return request.method.toUpperCase() + "&" + this.percentEncode(this.getBaseUrl(request.url)) + "&" + this.percentEncode(this.getParameterString(request, oauth_data));
	};
	/**
	* Get data from url
	* -> merge with oauth data
	* -> percent encode key & value
	* -> sort
	*
	* @param  {Object} request data
	* @param  {Object} OAuth data
	* @return {Object} Parameter string data
	*/
	OAuth$1.prototype.getParameterString = function(request, oauth_data) {
		var base_string_data;
		if (oauth_data.oauth_body_hash) base_string_data = this.sortObject(this.percentEncodeData(this.mergeObject(oauth_data, this.deParamUrl(request.url))));
		else base_string_data = this.sortObject(this.percentEncodeData(this.mergeObject(oauth_data, this.mergeObject(request.data, this.deParamUrl(request.url)))));
		var data_str = "";
		for (var i = 0; i < base_string_data.length; i++) {
			var key = base_string_data[i].key;
			var value = base_string_data[i].value;
			if (value && Array.isArray(value)) {
				value.sort();
				var valString = "";
				value.forEach((function(item, i$1) {
					valString += key + "=" + item;
					if (i$1 < value.length) valString += "&";
				}).bind(this));
				data_str += valString;
			} else data_str += key + "=" + value + "&";
		}
		data_str = data_str.substr(0, data_str.length - 1);
		return data_str;
	};
	/**
	* Create a Signing Key
	* @param  {String} token_secret Secret Token
	* @return {String} Signing Key
	*/
	OAuth$1.prototype.getSigningKey = function(token_secret) {
		token_secret = token_secret || "";
		if (!this.last_ampersand && !token_secret) return this.percentEncode(this.consumer.secret);
		return this.percentEncode(this.consumer.secret) + "&" + this.percentEncode(token_secret);
	};
	/**
	* Get base url
	* @param  {String} url
	* @return {String}
	*/
	OAuth$1.prototype.getBaseUrl = function(url) {
		return url.split("?")[0];
	};
	/**
	* Get data from String
	* @param  {String} string
	* @return {Object}
	*/
	OAuth$1.prototype.deParam = function(string) {
		var arr = string.split("&");
		var data = {};
		for (var i = 0; i < arr.length; i++) {
			var item = arr[i].split("=");
			item[1] = item[1] || "";
			if (data[item[0]]) {
				if (!Array.isArray(data[item[0]])) data[item[0]] = [data[item[0]]];
				data[item[0]].push(decodeURIComponent(item[1]));
			} else data[item[0]] = decodeURIComponent(item[1]);
		}
		return data;
	};
	/**
	* Get data from url
	* @param  {String} url
	* @return {Object}
	*/
	OAuth$1.prototype.deParamUrl = function(url) {
		var tmp = url.split("?");
		if (tmp.length === 1) return {};
		return this.deParam(tmp[1]);
	};
	/**
	* Percent Encode
	* @param  {String} str
	* @return {String} percent encoded string
	*/
	OAuth$1.prototype.percentEncode = function(str) {
		return encodeURIComponent(str).replace(/\!/g, "%21").replace(/\*/g, "%2A").replace(/\'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29");
	};
	/**
	* Percent Encode Object
	* @param  {Object} data
	* @return {Object} percent encoded data
	*/
	OAuth$1.prototype.percentEncodeData = function(data) {
		var result = {};
		for (var key in data) {
			var value = data[key];
			if (value && Array.isArray(value)) {
				var newValue = [];
				value.forEach((function(val) {
					newValue.push(this.percentEncode(val));
				}).bind(this));
				value = newValue;
			} else value = this.percentEncode(value);
			result[this.percentEncode(key)] = value;
		}
		return result;
	};
	/**
	* Get OAuth data as Header
	* @param  {Object} oauth_data
	* @return {String} Header data key - value
	*/
	OAuth$1.prototype.toHeader = function(oauth_data) {
		var sorted = this.sortObject(oauth_data);
		var header_value = "OAuth ";
		if (this.realm) header_value += "realm=\"" + this.realm + "\"" + this.parameter_seperator;
		for (var i = 0; i < sorted.length; i++) {
			if (sorted[i].key.indexOf("oauth_") !== 0) continue;
			header_value += this.percentEncode(sorted[i].key) + "=\"" + this.percentEncode(sorted[i].value) + "\"" + this.parameter_seperator;
		}
		return { Authorization: header_value.substr(0, header_value.length - this.parameter_seperator.length) };
	};
	/**
	* Create a random word characters string with input length
	* @return {String} a random word characters string
	*/
	OAuth$1.prototype.getNonce = function() {
		var word_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		var result = "";
		for (var i = 0; i < this.nonce_length; i++) result += word_characters[parseInt(Math.random() * word_characters.length, 10)];
		return result;
	};
	/**
	* Get Current Unix TimeStamp
	* @return {Int} current unix timestamp
	*/
	OAuth$1.prototype.getTimeStamp = function() {
		return parseInt((/* @__PURE__ */ new Date()).getTime() / 1e3, 10);
	};
	/**
	* Merge object
	* @param  {Object} obj1
	* @param  {Object} obj2
	* @return {Object}
	*/
	OAuth$1.prototype.mergeObject = function(obj1, obj2) {
		obj1 = obj1 || {};
		obj2 = obj2 || {};
		var merged_obj = obj1;
		for (var key in obj2) merged_obj[key] = obj2[key];
		return merged_obj;
	};
	/**
	* Sort object by key
	* @param  {Object} data
	* @return {Array} sorted array
	*/
	OAuth$1.prototype.sortObject = function(data) {
		var keys = Object.keys(data);
		var result = [];
		keys.sort();
		for (var i = 0; i < keys.length; i++) {
			var key = keys[i];
			result.push({
				key,
				value: data[key]
			});
		}
		return result;
	};
}) });

//#endregion
//#region src/index.ts
var import_oauth_1_0a = /* @__PURE__ */ __toESM(require_oauth_1_0a());
const signatures = {
	HMAC_SHA1: "HMAC-SHA1",
	HMAC_SHA256: "HMAC-SHA256",
	HMAC_SHA512: "HMAC-SHA512",
	RSA_SHA1: "RSA-SHA1",
	RSA_SHA256: "RSA-SHA256",
	RSA_SHA512: "RSA-SHA512",
	PLAINTEXT: "PLAINTEXT"
};
const defaultSig = signatures.HMAC_SHA1;
const pkSigs = Object.values(signatures).filter((k) => k.startsWith("RSA-"));
const nonPkSigs = Object.values(signatures).filter((k) => !pkSigs.includes(k));
function hiddenIfNot(sigMethod, ...other) {
	return (_ctx, { values }) => {
		const hasGrantType = sigMethod.find((t) => t === String(values.signatureMethod ?? defaultSig));
		const hasOtherBools = other.every((t) => t(values));
		return { hidden: !(hasGrantType && hasOtherBools) };
	};
}
const plugin = { authentication: {
	name: "oauth1",
	label: "OAuth 1.0",
	shortLabel: "OAuth 1",
	args: [
		{
			type: "banner",
			color: "info",
			inputs: [{
				type: "markdown",
				content: "OAuth 1.0 is still in beta. Please submit any issues to [Feedback](https://yaak.app/feedback)."
			}]
		},
		{
			name: "signatureMethod",
			label: "Signature Method",
			type: "select",
			defaultValue: defaultSig,
			options: Object.values(signatures).map((v) => ({
				label: v,
				value: v
			}))
		},
		{
			name: "consumerKey",
			label: "Consumer Key",
			type: "text",
			password: true,
			optional: true
		},
		{
			name: "consumerSecret",
			label: "Consumer Secret",
			type: "text",
			password: true,
			optional: true
		},
		{
			name: "tokenKey",
			label: "Access Token",
			type: "text",
			password: true,
			optional: true
		},
		{
			name: "tokenSecret",
			label: "Token Secret",
			type: "text",
			password: true,
			optional: true,
			dynamic: hiddenIfNot(nonPkSigs)
		},
		{
			name: "privateKey",
			label: "Private Key (RSA-SHA1)",
			type: "text",
			multiLine: true,
			optional: true,
			password: true,
			placeholder: "-----BEGIN RSA PRIVATE KEY-----\nPrivate key in PEM format\n-----END RSA PRIVATE KEY-----",
			dynamic: hiddenIfNot(pkSigs)
		},
		{
			type: "accordion",
			label: "Advanced",
			inputs: [
				{
					name: "callback",
					label: "Callback Url",
					type: "text",
					optional: true
				},
				{
					name: "verifier",
					label: "Verifier",
					type: "text",
					optional: true,
					password: true
				},
				{
					name: "timestamp",
					label: "Timestamp",
					type: "text",
					optional: true
				},
				{
					name: "nonce",
					label: "Nonce",
					type: "text",
					optional: true
				},
				{
					name: "version",
					label: "OAuth Version",
					type: "text",
					optional: true,
					defaultValue: "1.0"
				},
				{
					name: "realm",
					label: "Realm",
					type: "text",
					optional: true
				}
			]
		}
	],
	onApply(_ctx, { values, method, url }) {
		const consumerKey = String(values.consumerKey || "");
		const consumerSecret = String(values.consumerSecret || "");
		const signatureMethod = String(values.signatureMethod || signatures.HMAC_SHA1);
		const version = String(values.version || "1.0");
		const realm = String(values.realm || "") || void 0;
		const oauth = new import_oauth_1_0a.default({
			consumer: {
				key: consumerKey,
				secret: consumerSecret
			},
			signature_method: signatureMethod,
			version,
			hash_function: hashFunction(signatureMethod),
			realm
		});
		if (pkSigs.includes(signatureMethod)) oauth.getSigningKey = (tokenSecret) => tokenSecret || "";
		const requestUrl = new URL(url);
		const requestData = {
			method,
			url: requestUrl.toString(),
			includeBodyHash: false,
			data: {}
		};
		for (const key of requestUrl.searchParams.keys()) {
			if (key.startsWith("oauth_")) continue;
			const all = requestUrl.searchParams.getAll(key);
			const first = all[0];
			if (first == null) continue;
			requestData.data[key] = all.length > 1 ? all : first;
		}
		if (values.callback) requestData.data.oauth_callback = String(values.callback);
		if (values.nonce) requestData.data.oauth_nonce = String(values.nonce);
		if (values.timestamp) requestData.data.oauth_timestamp = String(values.timestamp);
		if (values.verifier) requestData.data.oauth_verifier = String(values.verifier);
		let token;
		if (pkSigs.includes(signatureMethod)) token = {
			key: String(values.tokenKey || ""),
			secret: String(values.privateKey || "")
		};
		else if (values.tokenKey && values.tokenSecret) token = {
			key: String(values.tokenKey),
			secret: String(values.tokenSecret)
		};
		else if (values.tokenKey) token = { key: String(values.tokenKey) };
		const authParams = oauth.authorize(requestData, token);
		const { Authorization } = oauth.toHeader(authParams);
		return { setHeaders: [{
			name: "Authorization",
			value: Authorization
		}] };
	}
} };
function hashFunction(signatureMethod) {
	switch (signatureMethod) {
		case signatures.HMAC_SHA1: return (base, key) => node_crypto.default.createHmac("sha1", key).update(base).digest("base64");
		case signatures.HMAC_SHA256: return (base, key) => node_crypto.default.createHmac("sha256", key).update(base).digest("base64");
		case signatures.HMAC_SHA512: return (base, key) => node_crypto.default.createHmac("sha512", key).update(base).digest("base64");
		case signatures.RSA_SHA1: return (base, privateKey) => node_crypto.default.createSign("RSA-SHA1").update(base).sign(privateKey, "base64");
		case signatures.RSA_SHA256: return (base, privateKey) => node_crypto.default.createSign("RSA-SHA256").update(base).sign(privateKey, "base64");
		case signatures.RSA_SHA512: return (base, privateKey) => node_crypto.default.createSign("RSA-SHA512").update(base).sign(privateKey, "base64");
		case signatures.PLAINTEXT: return (base) => base;
		default: return (base, key) => node_crypto.default.createHmac("sha1", key).update(base).digest("base64");
	}
}

//#endregion
exports.plugin = plugin;