import { API_URL } from '$env/static/private'; import { error, redirect, type Actions } from '@sveltejs/kit'; import { compile } from 'mdsvex'; import type { PageServerLoad } from './$types'; import type Puzzle from '$lib/components/puzzle.svelte'; import type { Chapter } from '$lib/types'; import { handleRedirect } from '$lib/utils'; export const load = (async ({ url, locals: { user }, fetch, cookies, params: { chapterId, puzzleId } }) => { if (!user) redirect(302, handleRedirect('login', url)); const session = cookies.get('session'); if (isNaN(parseInt(puzzleId))) { redirect(302, `/chapters/${chapterId}`); } let res = await fetch(`${API_URL}/chapter/${chapterId}`, { headers: { Authorization: `Bearer ${session}` } }); if (!res.ok) { redirect(302, `/chapters`); } const chapter = (await res.json()) as Chapter; if (!chapter || !chapter.show) { redirect(302, `/chapters`); } if ( !chapter.puzzles.some((puzzle) => puzzle.id === parseInt(puzzleId)) || !chapter.puzzles.find((puzzle) => puzzle.id === parseInt(puzzleId))?.show ) { redirect(302, `/chapters/${chapterId}`); } res = await fetch(`${API_URL}/puzzle/${puzzleId}`, { headers: { Authorization: `Bearer ${session}` } }); if (!res.ok) { error(404, 'Puzzle not found'); } const puzzle: Puzzle = await res.json(); if (!puzzle) { error(404, 'Puzzle not found'); } const content = await compile(puzzle.content); puzzle.content = content?.code .replace(/>{@html ``}<\/pre>/g, ''); return { title: `${chapter.name} - ${puzzle.name}`, puzzle: puzzle as Puzzle, url: `${API_URL}/puzzleResponse/${puzzleId}`, session }; }) satisfies PageServerLoad; export const actions = { default: async ({ params }) => { redirect(302, `/chapters/${params.chapterId}/puzzle/${params.puzzleId}`); } } satisfies Actions;