cloud / internal-packages / installer / src / your-deployments.tsmain at aacbc74
// "Your deployments": what the page (Deployments.tsx), the sidebar (CloudNav.tsx) and the way in
// (the routes in main.tsx) share. The Worker's side is worker/deployments.js: every answer is read
// from the person's own Cloudflare account and from the deployments themselves, when it is asked.
import { redirect } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useSyncExternalStore } from "react";
import { z } from "zod";
import {
boot,
call,
deployPath,
errorOf,
queryClient,
setState,
useGet,
useWizard,
type State,
} from "./api.ts";
const Account = z.object({ id: z.string(), name: z.string() });
/** One deployment, as worker/deployments.js answers it. */
const Deployment = z.object({
account: Account,
domain: z.string(),
zone: z.object({
id: z.string(),
name: z.string(),
status: z.string(),
nameServers: z.array(z.string()),
}),
name: z.string(),
/** It answers as an issuer at iterate.<domain>. */
answers: z.boolean(),
/** Its Dash answers at dash.<domain>, where the onboarding chat is. */
onboarding: z.boolean(),
/** When Cloudflare says its boundary Worker last changed. */
changedAt: z.string().nullable(),
/** The deploy run this Cloud made for it, if it made one. */
run: z
.object({
status: z.string(),
endedAt: z.number().nullable(),
commit: z.string().nullable(),
/** Each Worker's version before and after that run: the proof of an update. */
versions: z
.record(z.string(), z.object({ before: z.string().nullish(), after: z.string().nullish() }))
.nullable()
.default(null),
/** That run's deploy made or kept the mind's Cloudflare connection. */
cloudflareToken: z.boolean().default(false),
/** And the connection's token holds this release's list: else an update narrows it. */
cloudflareTokenCurrent: z.boolean().default(true),
})
.nullable(),
/** The commit of iterate it runs, when its boundary Worker or this Cloud's record says it. */
commit: z.string().nullable().default(null),
/** It runs an iterate that this Cloud does not have: a newer one, or one from another branch.
* `cloud` is the commit an update from here would put over it. The run refuses, but for
* "Update anyway". */
foreign: z.object({ runs: z.string(), cloud: z.string() }).nullable().default(null),
/** It is from before the rename: a deploy run stops at it, and the way on is the erase. */
older: z.boolean().default(false),
/** It has its telemetry Worker: it keeps its own events, logs and traces. */
telemetry: z.boolean().default(false),
/** Parts of a stack, and no Worker that serves the domain: a deploy or an erase that did not
* finish. The way on is the erase. */
incomplete: z.boolean().default(false),
/** An update can start from here: of a stack this Cloud deployed, and of one that somebody
* deployed another way and that serves the domain. */
updatable: z.boolean(),
replaceable: z.boolean(),
/** Its vault key is kept outside Cloudflare: a run from here stopped at that, so no update. */
keyOutside: z.boolean().default(false),
/** Why no erase is offered: the Cloud's own domain, or one that serves another Worker. */
noErase: z.string().nullable().default(null),
/** The address that signs in to it, as the person gave it at its first deploy from here. */
owner: z.string().nullable().default(null),
enrolled: z.boolean(),
/** iterate's shared apps that deliver to it: the client, and how many accounts at it. */
apps: z.record(z.string(), z.number()),
});
export type Deployment = z.infer<typeof Deployment>;
/** `GET /api/deployments`; a refusal has neither list. */
const FoundAnswer = z.object({
deployments: z.array(Deployment).default([]),
notes: z.array(z.string()).default([]),
});
/** `GET /api/me`, as the wizard's own state holds it (api.ts `State["me"]`). */
const MeAnswer = z.object({
connected: z.boolean().optional(),
level: z.enum(["identity", "full"]).optional(),
missing: z.array(z.string()).optional(),
telemetry: z.boolean().optional(),
cloudflareToken: z.boolean().optional(),
user: z.object({ email: z.string(), name: z.string() }),
accounts: z.array(Account).default([]),
domains: z.number().nullish(),
created: Account.nullish(),
});
type Me = NonNullable<State["me"]>;
/** A read that changes nothing on the page: no row in the wizard's log, and a refusal does not
* send the wizard to its sign-in. What it said is for its caller to parse. */
async function quiet(path: string) {
const answer = await fetch(path).catch(() => null);
const said: unknown = await answer?.json().catch(() => null);
return { ok: !!answer?.ok, status: answer?.status || 0, said };
}
const found = {
queryKey: ["quiet", "/api/deployments"],
queryFn: async () => {
const { ok, status, said } = await quiet("/api/deployments");
const parsed = FoundAnswer.safeParse(said);
return {
ok: ok && parsed.success,
status,
deployments: parsed.data?.deployments || [],
notes: parsed.data?.notes || [],
};
},
staleTime: 30_000,
};
/** Who is signed in: the wizard's own answer when it has one (it asks at its start), else asked
* here, for a page that was opened by its address. */
export function useMe(): { me: Me | null; asked: boolean } {
const wizard = useWizard().me;
const own = useQuery({
queryKey: ["quiet", "/api/me"],
// nobody signed in: the answer names no user, and does not parse
queryFn: async (): Promise<Me | null> =>
MeAnswer.safeParse((await quiet("/api/me")).said).data || null,
enabled: !wizard,
staleTime: 30_000,
});
if (wizard) return { me: wizard, asked: true };
return { me: own.data || null, asked: !own.isPending };
}
// ── the words on the wait ──
// The list is read from Cloudflare when it is asked: every domain of the account, and the routes
// of up to 40 of them. An account with hundreds of domains takes seconds, so the page says what
// it waits for, and how much there is to read.
/** What the page says while the list is read. `domains`: how many the access reads, if known. */
export const readingWords = (domains: number | null | undefined) =>
(domains ?? 0) > 1
? `Reading your Cloudflare account: ${domains} domains…`
: "Reading your Cloudflare account…";
/** The way in is reading the list (`enterWizard`): null before and after. */
let reading: { domains: number | null } | null = null;
const readers = new Set<() => void>();
const subscribeToReading = (reader: () => void) => {
readers.add(reader);
return () => void readers.delete(reader);
};
function setReading(next: typeof reading) {
reading = next;
for (const reader of readers) reader();
}
/** For the wizard's route while its loader goes (Deployments.tsx `Entering`). */
export const useReading = () => useSyncExternalStore(subscribeToReading, () => reading);
/** The deployments, while there is access to Cloudflare to read them with. */
export const useDeployments = (connected: boolean) => useQuery({ ...found, enabled: connected });
/** The domain that this tab's wizard deployed iterate on, for the list while it has no access to
* Cloudflare: the Cloud's own record of the run answers with no token (GET /api/deploy). Null
* when the tab deployed none, or its run did not succeed. */
export function useJustDeployed(asks: boolean) {
const s = useWizard();
const path = asks ? deployPath(s) : null;
const status = useGet(path).data?.state?.status;
return path && status === "succeeded" ? s.result?.name || null : null;
}
// ── the way in ──
// A person whose account already holds iterate lands on the list, not in the wizard. Not when
// this tab is in the middle of something: a domain is chosen, or they asked for the wizard. That
// choice is this tab's, so it is in sessionStorage beside the wizard's own state.
const ASKED_FOR_WIZARD = "wizardAsked";
const tab = (key: string) => {
try {
return sessionStorage.getItem(key);
} catch {
return null;
}
};
/** The wizard is what they want in this tab: a new deployment. */
export function askForWizard() {
try {
sessionStorage.setItem(ASKED_FOR_WIZARD, "1");
} catch {}
}
/** A NEW DEPLOYMENT STARTS AT THE WIZARD'S FIRST QUESTION, whoever is signed in: a new Cloudflare
* account, or one they have. A person who is connected already would otherwise land past that
* question, on the account their consent named, with no way on the page to a new account. What
* this tab's wizard held about another deployment (its domain, its run) is dropped; who is signed
* in, and an account this person made here before, stay.
*
* The wizard's own start comes first (`boot`): it asks who is signed in and ends on a state of
* its own, which would undo this one. The caller goes to the wizard after this resolves. */
export async function startNewDeployment() {
askForWizard();
await boot();
setState({
step: 0,
maxStep: 0,
choosing: true,
want: "new",
needsAccess: false,
path: null,
choice: null,
zone: null,
result: null,
error: null,
tried: {},
finished: false,
recovering: false,
});
}
/** The consent was asked from the list: it comes back to the list, whatever this tab was doing. */
const BACK_TO_LIST = "wizardBackToList";
export function comeBackToList() {
try {
sessionStorage.setItem(BACK_TO_LIST, "1");
} catch {}
}
/** What this tab's wizard holds (api.ts keeps its state under "wizard"), of what the way in
* reads. None when the tab has none, or one that does not parse. */
const TabWizard = z.object({
me: z
.object({
connected: z.boolean().optional(),
level: z.string().optional(),
domains: z.number().nullish(),
})
.nullish(),
result: z.unknown().optional(),
zone: z.unknown().optional(),
});
function tabWizard() {
try {
return TabWizard.parse(JSON.parse(tab("wizard") || "null"));
} catch {
return null;
}
}
/** The loader of the wizard's route: its own start, then the list when there is one to show. */
export async function enterWizard() {
await boot();
if (tab(BACK_TO_LIST)) {
try {
sessionStorage.removeItem(BACK_TO_LIST);
} catch {}
throw redirect({ to: "/deployments" });
}
if (tab(ASKED_FOR_WIZARD)) return;
const wizard = tabWizard();
if (!wizard?.me?.connected || wizard.me.level === "identity" || wizard.result || wizard.zone)
return;
setReading({ domains: wizard.me.domains ?? null });
const answer = await queryClient.fetchQuery(found).catch(() => null);
setReading(null);
if (answer?.ok && answer.deployments.length > 0) throw redirect({ to: "/deployments" });
}
/** The wizard's Deploy step on a deployment: the run's steps while one goes, and what it made.
* The wizard's "Try again" after a run that failed starts a deploy for the address in its own
* state, so that address is the deployment's owner from here on, never whoever is signed in. */
export function openInWizard(
deployment: Pick<Deployment, "account" | "domain" | "zone" | "owner">,
) {
// the account first: a change of account clears what belongs to the one before
setState({ account: deployment.account.id });
setState({
// oxlint-disable-next-line iterate/simple-truthiness-check -- setState spreads the patch, so an email key set to undefined would clear the wizard's email; with no owner the key must stay absent
...(deployment.owner && { email: deployment.owner }),
want: "existing",
choosing: false,
needsAccess: false,
path: "have",
mode: "production",
zone: deployment.zone,
result: { name: deployment.domain, how: "have" },
step: 3,
error: null,
recovering: false,
});
}
/** Starts an update of a deployment this Cloud made, from the list. `recover`: the owner lost
* every passkey, so the update also makes a link that signs them in once. For a deployment that
* runs an iterate this Cloud does not have, it is "Update anyway": the request names the commit
* the person saw, and the run replaces that one alone. Answers what went wrong, or null: the run
* goes, and the wizard's Deploy step shows it. */
export async function startUpdate(deployment: Deployment, recover: boolean) {
const started = await call("POST", "/api/deploy", {
account: deployment.account.id,
zone: deployment.domain,
zoneId: deployment.zone.id,
...(recover && { recover: true }),
...(deployment.foreign && { anyway: deployment.foreign.runs }),
});
// the access to Cloudflare is over, or the run took it: the list asks again either way
void queryClient.invalidateQueries({ queryKey: ["quiet"] });
if (started.status === 401) return "Your access to Cloudflare ended. Connect Cloudflare again.";
if (!started.ok) return errorOf(started);
// what the wizard's Deploy step reads (Wizard.tsx `deployPath`): it shows the run at once
queryClient.setQueryData(
[`/api/deploy?account=${deployment.account.id}&zone=${deployment.domain}`],
started,
);
setState((wizard) => ({ me: wizard.me && { ...wizard.me, connected: !!started.connected } }));
openInWizard(deployment);
return null;
}
const LABELS: Record<string, string> = {
github: "GitHub",
google: "Google",
slack: "Slack",
x: "X",
};
/** iterate's shared apps, each with how many accounts at it deliver to the deployment. */
export const appsOf = (deployment: Deployment) =>
Object.entries(LABELS).map(([client, label]) => ({
client,
label,
accounts: deployment.apps[client] || 0,
}));
/** `2026-11-11`, from a time Cloudflare or the run gave. */
export const dayOf = (at: string | number | null) => {
const time = at ? new Date(at) : null;
return time && !Number.isNaN(time.getTime()) ? time.toISOString().slice(0, 10) : null;
};