import { parseUrlComponents } from "../components.js";
import { LogSource, LoggerContext } from "../../logging/logger_transport.js";
import { createLogger } from "../../logging/logger.js";
import { X_RESTATE_SERVER } from "../../user_agent.js";

//#region src/endpoint/handlers/utils.ts
function tryCreateContextualLogger(loggerTransport, url, headers, additionalContext) {
	try {
		const path = new URL(url, "https://example.com").pathname;
		const parsed = parseUrlComponents(path);
		if (parsed.type !== "invoke") return;
		const invocationId = invocationIdFromHeaders(headers);
		return createLogger(loggerTransport, LogSource.SYSTEM, new LoggerContext(invocationId, parsed.componentName, parsed.handlerName, void 0, void 0, additionalContext));
	} catch {
		return;
	}
}
function invocationIdFromHeaders(headers) {
	const invocationIdHeader = headers["x-restate-invocation-id"];
	return typeof invocationIdHeader === "string" ? invocationIdHeader : Array.isArray(invocationIdHeader) ? invocationIdHeader[0] ?? "unknown id" : "unknown id";
}
function errorResponse(code, message) {
	return simpleResponse(code, {
		"content-type": "application/json",
		"x-restate-server": X_RESTATE_SERVER
	}, new TextEncoder().encode(JSON.stringify({ message })));
}
function simpleResponse(statusCode, headers, body) {
	return { async process({ inputReader, outputWriter, writeHead }) {
		writeHead(statusCode, headers);
		while (true) {
			const { done } = await inputReader.next();
			if (done) break;
		}
		await outputWriter.write(body);
		await outputWriter.close();
	} };
}
function emptyInputReader() {
	return (async function* () {})()[Symbol.asyncIterator]();
}
/**
* Bundles a `writeHead` callback with a Promise that resolves once the head
* is committed. Used by adapters (fetch, lambda) that need to observe the
* head commit from outside the `process()` call.
*/
function captureHead() {
	const { promise, resolve } = Promise.withResolvers();
	return {
		writeHead: (statusCode, headers) => {
			resolve({
				statusCode,
				headers: { ...headers }
			});
		},
		head: promise
	};
}

//#endregion
export { captureHead, emptyInputReader, errorResponse, invocationIdFromHeaders, simpleResponse, tryCreateContextualLogger };
//# sourceMappingURL=utils.js.map