qs.js 3.18 KB
export const formats = {
	default: "RFC3986",
	formatters: {
		RFC1738(value) {
			return String(value).replaceAll("%20", "+");
		},
		RFC3986: String,
	},
	RFC1738: "RFC1738",
	RFC3986: "RFC3986",
};

function decodeValue(input) {
	try {
		return decodeURIComponent(String(input).replaceAll("+", " "));
	} catch {
		return String(input);
	}
}

function encodeValue(input) {
	return encodeURIComponent(String(input));
}

function isPlainObject(value) {
	if (!value || typeof value !== "object") return false;
	const proto = Object.getPrototypeOf(value);
	return proto === Object.prototype || proto === null;
}

function addEntry(entries, key, value, options) {
	if (value === undefined) return;
	if (options.skipNulls && value === null) return;

	const keyOut = options.encodeValuesOnly ? key : encodeValue(key);
	if (value === null && options.strictNullHandling) {
		entries.push(keyOut);
		return;
	}

	const valueOut = encodeValue(value === null ? "" : value);
	entries.push(`${keyOut}=${valueOut}`);
}

function buildEntries(entries, value, key, options) {
	if (value === undefined) return;

	if (value instanceof Date) {
		addEntry(entries, key, options.serializeDate(value), options);
		return;
	}

	if (Array.isArray(value)) {
		value.forEach((v, idx) => {
			let nextKey = key;
			if (options.arrayFormat === "indices") nextKey = `${key}[${idx}]`;
			else if (options.arrayFormat === "brackets") nextKey = `${key}[]`;
			buildEntries(entries, v, nextKey, options);
		});
		return;
	}

	if (isPlainObject(value)) {
		for (const [k, v] of Object.entries(value)) {
			const nextKey = options.allowDots ? `${key}.${k}` : `${key}[${k}]`;
			buildEntries(entries, v, nextKey, options);
		}
		return;
	}

	addEntry(entries, key, value, options);
}

export function stringify(object, opts = {}) {
	const options = {
		delimiter: "&",
		allowDots: false,
		encodeValuesOnly: false,
		arrayFormat: "indices",
		addQueryPrefix: false,
		skipNulls: false,
		strictNullHandling: false,
		serializeDate: (d) => d.toISOString(),
		...opts,
	};

	if (!object || typeof object !== "object") return "";

	const entries = [];
	const keys = Object.keys(object);
	if (typeof options.sort === "function") keys.sort(options.sort);

	for (const key of keys) {
		buildEntries(entries, object[key], key, options);
	}

	const joined = entries.join(options.delimiter);
	if (!joined) return "";
	return options.addQueryPrefix ? `?${joined}` : joined;
}

export function parse(str, opts = {}) {
	const options = {
		ignoreQueryPrefix: false,
		delimiter: "&",
		...opts,
	};

	const input = options.ignoreQueryPrefix ? String(str).replace(/^\?/, "") : String(str);
	if (!input) return {};

	const out = {};
	const parts = input.split(options.delimiter);
	for (const part of parts) {
		if (!part) continue;
		const idx = part.indexOf("=");
		const rawKey = idx === -1 ? part : part.slice(0, idx);
		const rawValue = idx === -1 ? "" : part.slice(idx + 1);
		const key = decodeValue(rawKey);
		const value = decodeValue(rawValue);

		if (Object.hasOwn(out, key)) {
			const prev = out[key];
			out[key] = Array.isArray(prev) ? [...prev, value] : [prev, value];
		} else {
			out[key] = value;
		}
	}
	return out;
}

const Qs = { formats, parse, stringify };
export default Qs;