import { Authentication } from "$modules/authentication.ts";
import type { VP_Request } from "$modules/vp_request.ts";
import { ServeTyped } from "$utils/serve_ts.ts";
import { join } from "$std/path/mod.ts";
import { ValidResponseType } from "./api/router.ts";
import { HandleRequest } from "$modules/handle_request.ts";
const cwd = import.meta.dirname || Deno.cwd();
export const DenoRouter = async (request: VP_Request, info: Deno.ServeHandlerInfo<Deno.NetAddr>): Promise<Response> => {
try {
const has_access = Authentication(request);
if(!has_access) throw new Deno.errors.ConnectionRefused;
const method = request.method.toUpperCase();
if(method == 'GET') {
if(!has_access && request.pathname == '/') {
return ServeTyped(join(cwd, 'cli/no_access.ts'), { status: 200 });
}
if([
'/config.ts',
'/utils/meta_path.ts',
'/utils/sleep.ts',
'/utils/fetch_external.ts',
].includes(request.pathname)) {
return ServeTyped(join(cwd, `/cli/${request.pathname}`));
}
if(!has_access) return new Response(null, { status: 403 });
if(request.pathname == '/') {
return ServeTyped(join(cwd, 'viapak.ts'));
} else if(request.pathname == '/deno.json') {
return ServeTyped(join(cwd, 'deno.json'));
} else if(request.pathname.indexOf('/cli') == 0) {
return ServeTyped(join(cwd, request.pathname));
};
if([
'/utils/read_file.ts',
'/utils/scan_files.ts',
'/utils/file_size.ts',
'/utils/sort_utils.ts',
'/utils/version_helpers.ts',
'/modules/zip.ts',
].includes(request.pathname)) {
return ServeTyped(join(cwd, request.pathname));
}
}
if(!has_access) return new Response(null, { status: 403 });
let response: ValidResponseType = undefined;
response = await HandleRequest(request, info);
if(response instanceof Response) return response;
if(typeof response === 'number') {
return new Response(null, { status: response });
}
if(typeof response === 'object' && !(response instanceof Response)) {
let status = 200;
if(response.status) {
if(typeof response.status === 'number') {
status = response.status;
}
delete response.status;
}
return Response.json(response, { status });
}
if(!response) throw new Deno.errors.NotFound;
return response;
} catch(e: any) {
let status = 500;
if(e instanceof Deno.errors.ConnectionRefused) status = 401;
if(e instanceof Deno.errors.NotFound) status = 404;
if(e instanceof Deno.errors.PermissionDenied) status = 403;
return new Response(null, { status });
}
}