import { contentType, Status, STATUS_TEXT } from "./deps.ts";import { DomResponse } from "./http_server_native_request.ts";import type { Request } from "./request.ts";import { BODY_TYPES, encodeUrl, isAsyncIterable, isHtml, isReader, isRedirectStatus, readableStreamFromAsyncIterable, readableStreamFromReader, Uint8ArrayTransformStream,} from "./util.ts";
export type ResponseBody = | string | number | bigint | boolean | symbol | object | undefined | null;export type ResponseBodyFunction = () => ResponseBody | Promise<ResponseBody>;
export const REDIRECT_BACK = Symbol("redirect backwards");
export async function convertBodyToBodyInit( body: ResponseBody | ResponseBodyFunction, type?: string, jsonBodyReplacer?: (key: string, value: unknown) => unknown,): Promise<[globalThis.BodyInit | undefined, string | undefined]> { let result: globalThis.BodyInit | undefined; if (BODY_TYPES.includes(typeof body)) { result = String(body); type = type ?? (isHtml(result) ? "html" : "text/plain"); } else if (isReader(body)) { result = readableStreamFromReader(body); } else if ( ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof Blob || body instanceof URLSearchParams ) { result = body as any; } else if (body instanceof ReadableStream) { result = body.pipeThrough(new Uint8ArrayTransformStream()); } else if (body instanceof FormData) { result = body; type = "multipart/form-data"; } else if (isAsyncIterable(body)) { result = readableStreamFromAsyncIterable(body); } else if (body && typeof body === "object") { result = JSON.stringify(body, jsonBodyReplacer); type = type ?? "json"; } else if (typeof body === "function") { const result = body.call(null); return convertBodyToBodyInit(await result, type, jsonBodyReplacer); } else if (body) { throw new TypeError("Response body was set but could not be converted."); } return [result, type];}
export class Response { #body?: ResponseBody | ResponseBodyFunction; #bodySet = false; #domResponse?: globalThis.Response; #headers = new Headers(); #jsonBodyReplacer?: (key: string, value: unknown) => unknown; #request: Request; #resources: number[] = []; #status?: Status; #type?: string; #writable = true;
async #getBodyInit(): Promise<globalThis.BodyInit | undefined> { const [body, type] = await convertBodyToBodyInit( this.body, this.type, this.#jsonBodyReplacer, ); this.type = type; return body; }
#setContentType(): void { if (this.type) { const contentTypeString = contentType(this.type); if (contentTypeString && !this.headers.has("Content-Type")) { this.headers.append("Content-Type", contentTypeString); } } }
get body(): ResponseBody | ResponseBodyFunction { return this.#body; }
set body(value: ResponseBody | ResponseBodyFunction) { if (!this.#writable) { throw new Error("The response is not writable."); } this.#bodySet = true; this.#body = value; }
get headers(): Headers { return this.#headers; }
set headers(value: Headers) { if (!this.#writable) { throw new Error("The response is not writable."); } this.#headers = value; }
get status(): Status { if (this.#status) { return this.#status; } return this.body != null ? Status.OK : this.#bodySet ? Status.NoContent : Status.NotFound; }
set status(value: Status) { if (!this.#writable) { throw new Error("The response is not writable."); } this.#status = value; }
get type(): string | undefined { return this.#type; } set type(value: string | undefined) { if (!this.#writable) { throw new Error("The response is not writable."); } this.#type = value; }
get writable(): boolean { return this.#writable; }
constructor( request: Request, jsonBodyReplacer?: (key: string, value: unknown) => unknown, ) { this.#request = request; this.#jsonBodyReplacer = jsonBodyReplacer; }
addResource(rid: number): void { this.#resources.push(rid); }
destroy(closeResources = true): void { this.#writable = false; this.#body = undefined; this.#domResponse = undefined; if (closeResources) { for (const rid of this.#resources) { try { Deno.close(rid); } catch { } } } }
redirect(url: string | URL): void; redirect(url: typeof REDIRECT_BACK, alt?: string | URL): void; redirect( url: string | URL | typeof REDIRECT_BACK, alt: string | URL = "/", ): void { if (url === REDIRECT_BACK) { url = this.#request.headers.get("Referer") ?? String(alt); } else if (typeof url === "object") { url = String(url); } this.headers.set("Location", encodeUrl(url)); if (!this.status || !isRedirectStatus(this.status)) { this.status = Status.Found; }
if (this.#request.accepts("html")) { url = encodeURI(url); this.type = "text/html; charset=UTF-8"; this.body = `Redirecting to <a href="${url}">${url}</a>.`; return; } this.type = "text/plain; charset=UTF-8"; this.body = `Redirecting to ${url}.`; }
async toDomResponse(): Promise<globalThis.Response> { if (this.#domResponse) { return this.#domResponse; }
const bodyInit = await this.#getBodyInit();
this.#setContentType();
const { headers } = this;
if ( !( bodyInit || headers.has("Content-Type") || headers.has("Content-Length") ) ) { headers.append("Content-Length", "0"); }
this.#writable = false;
const status = this.status; const responseInit: ResponseInit = { headers, status, statusText: STATUS_TEXT[status], };
return this.#domResponse = new DomResponse(bodyInit, responseInit); }
[Symbol.for("Deno.customInspect")](inspect: (value: unknown) => string) { const { body, headers, status, type, writable } = this; return `${this.constructor.name} ${ inspect({ body, headers, status, type, writable }) }`; }
[Symbol.for("nodejs.util.inspect.custom")]( depth: number, options: any, inspect: (value: unknown, options?: unknown) => string, ) { if (depth < 0) { return options.stylize(`[${this.constructor.name}]`, "special"); }
const newOptions = Object.assign({}, options, { depth: options.depth === null ? null : options.depth - 1, }); const { body, headers, status, type, writable } = this; return `${options.stylize(this.constructor.name, "special")} ${ inspect( { body, headers, status, type, writable }, newOptions, ) }`; }}