staging-tester / ocean-landing-serve / src/ routes/ (app)/ +layout.ts

import { goto, invalidateAll } from '$app/navigation';
import { redirect } from '@sveltejs/kit';
import { panesCookie, readPanes } from '#lib/components/app/shell.svelte.js';
import { clearBoot, readBoot, writeBoot } from '#lib/live/boot.js';
import { account, loadAccount } from '#lib/live/account.svelte.js';
import { loadPolicy } from '#lib/live/caissons.svelte.js';
import { ApiFailure } from '#lib/live/http.js';
import { identity, loadMe } from '#lib/live/identity.svelte.js';
import { loadOrg, org } from '#lib/live/org.svelte.js';
import { request } from '#lib/live/http.js';
import { loadProfile, privateRepos, profile } from '#lib/live/profile.svelte.js';
import type { LayoutLoad } from './$types';

// The app renders from the local-first store in the browser, so it never waits on a server render.
export const ssr = false;

const signIn = (path: string) => `/sign-in?next=${encodeURIComponent(path)}`;
const plain = <T>(value: T): T => JSON.parse(JSON.stringify(value));

// The panes cookie is read here, in the browser, so a client navigation never needs the server.
const readPaneCookie = () => {
	const raw = document.cookie.split('; ').find((c) => c.startsWith(`${panesCookie}=`));
	return readPanes(raw?.slice(panesCookie.length + 1));
};

// The org the shell shows: the one last opened, else the first the person belongs to; none leaves the org empty.
async function loadShellOrg() {
	if (org.handle) {
		await loadOrg(org.handle);
		return;
	}
	const [first] = await request<{ handle: string }[]>('GET', '/api/me/orgs');
	if (first) await loadOrg(first.handle);
}

// Fetches everything the shell renders from and keeps a copy for the next boot. Null when the server says signed out.
async function fetchAll() {
	const me = await loadMe();
	if (!me) return null;
	await Promise.all([loadProfile(me.handle), loadAccount(), loadShellOrg(), loadPolicy()]);
	writeBoot({ me, org: plain(org), profile: plain(profile), account: plain(account), privateRepos: [...privateRepos.names] });
	return me;
}

// A previous session boots the app at once, even offline, and the network revalidates it in the background; only a
// 401 from the server (never a failed fetch) sends you to sign in. With nothing cached, the first visit waits for the
// network and a failed one goes to sign-in, as it always did.
export const load: LayoutLoad = async ({ url }) => {
	const panes = readPaneCookie();
	const boot = readBoot();
	if (boot) {
		identity.me = boot.me;
		Object.assign(org, boot.org);
		Object.assign(profile, boot.profile);
		Object.assign(account, boot.account);
		privateRepos.names = boot.privateRepos;
		void fetchAll().then(
			(me) => {
				// A GitHub sign-in lands here without the sign-in page clearing the copy, which may be another account's.
				if (me && me.handle !== boot.me.handle) void invalidateAll();
				if (me) return;
				clearBoot();
				void goto(signIn(location.pathname + location.search), { replace: true });
			},
			() => undefined
		);
		return { panes, me: boot.me };
	}
	let me = null;
	try {
		me = await fetchAll();
	} catch (err) {
		if (err instanceof ApiFailure) throw err;
	}
	if (!me) redirect(307, signIn(url.pathname + url.search));
	return { panes, me };
};