@12-apps/tenant 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,273 @@
1
+ /**
2
+ * The CHECK pass of the domain operations: every operation is read against
3
+ * the tenant's domains and every other tenant's live names, and turned into
4
+ * the step it will take, or a named problem. Pure: nothing is read, written or
5
+ * asked of DNS here; the engine (`./engine.ts`) reads what this needs first.
6
+ *
7
+ * Problems are KINDS, never sentences or wire codes: the host maps each kind
8
+ * to its own code and its own words.
9
+ */
10
+ import { isZoneApex, wwwCompanionOf } from './dns-names';
11
+ import { hostnameOrNull } from './hostname';
12
+ import type { TenantDomainRecord } from './record';
13
+
14
+ /** One operation on a tenant's domains. A removal and a restore may carry a reason. */
15
+ export type TenantDomainOperation =
16
+ | { operation: 'add'; hostname: string; principal?: 'root' | 'www' }
17
+ | { operation: 'verify'; id?: string; hostname?: string }
18
+ | { operation: 'setPrincipal'; id?: string; hostname?: string; principal: 'root' | 'www' }
19
+ | { operation: 'archive' | 'restore'; id?: string; hostname?: string; reason?: string };
20
+
21
+ export type TenantDomainProblemKind =
22
+ | 'invalidHostname'
23
+ | 'nameTaken'
24
+ | 'nameHeldHere'
25
+ | 'planLimit'
26
+ | 'planRequired'
27
+ | 'notFound'
28
+ | 'notAPair'
29
+ | 'nameNotFree'
30
+ | 'removed'
31
+ | 'duplicateTarget'
32
+ | 'retry';
33
+
34
+ /**
35
+ * One refused operation (`index`), or the call as a whole (`index: null`, a
36
+ * race found in the transaction). `hostname` is the name the problem is about;
37
+ * `input` is what was typed, for `invalidHostname`.
38
+ */
39
+ export interface TenantDomainProblem {
40
+ index: number | null;
41
+ kind: TenantDomainProblemKind;
42
+ hostname: string | null;
43
+ input?: string;
44
+ }
45
+
46
+ /** What one checked operation will do. */
47
+ export type TenantDomainStep =
48
+ | { index: number; kind: 'add'; hostname: string; names: string[]; principal: 'root' | 'www' }
49
+ | { index: number; kind: 'noop'; domain: TenantDomainRecord }
50
+ | { index: number; kind: 'principal'; domain: TenantDomainRecord; principal: 'root' | 'www' }
51
+ | { index: number; kind: 'verify'; domain: TenantDomainRecord }
52
+ | { index: number; kind: 'archive'; domain: TenantDomainRecord; reason: string | null }
53
+ | { index: number; kind: 'restore'; domain: TenantDomainRecord; reason: string | null };
54
+
55
+ type AddOperation = Extract<TenantDomainOperation, { operation: 'add' }>;
56
+ type TargetOperation = Exclude<TenantDomainOperation, { operation: 'add' }>;
57
+
58
+ const isLive = (domain: TenantDomainRecord) => domain.archivedAt === null;
59
+
60
+ /** Every name a domain answers on, root first. */
61
+ export const namesOf = (domain: TenantDomainRecord): string[] => domain.names.map((name) => name.hostname);
62
+
63
+ /** The names a claim takes: the root and its `www.`, or the one subdomain. */
64
+ export function claimOf(host: string): string[] {
65
+ const www = wwwCompanionOf(host);
66
+ return www === null ? [host] : [host, www];
67
+ }
68
+
69
+ /**
70
+ * The names a claim must find free in OTHER tenants: its own, and, for a `www.`
71
+ * of a root domain, that root, whose `www.` belongs to whoever holds it (a root
72
+ * claimed before the pair existed has no `www.` row of its own).
73
+ */
74
+ export function guardedOf(host: string): string[] {
75
+ const parent = host.startsWith('www.') ? host.slice(4) : null;
76
+ return parent !== null && isZoneApex(parent) ? [...claimOf(host), parent] : claimOf(host);
77
+ }
78
+
79
+ /** The tenant's domain an operation names: by id, or by either name (a live one first; for a restore, the latest removed). */
80
+ function targetOf(domains: readonly TenantDomainRecord[], operation: TargetOperation): TenantDomainRecord | null {
81
+ if (operation.id !== undefined) return domains.find((domain) => domain.id === operation.id) ?? null;
82
+ const host = hostnameOrNull(operation.hostname ?? '');
83
+ if (host === null) return null;
84
+ const matching = domains.filter((domain) => namesOf(domain).includes(host));
85
+ const removed = matching
86
+ .filter((domain) => !isLive(domain))
87
+ .sort((a, b) => (b.archivedAt?.getTime() ?? 0) - (a.archivedAt?.getTime() ?? 0));
88
+ const live = matching.filter(isLive);
89
+ return (operation.operation === 'restore' ? (removed[0] ?? live[0]) : (live[0] ?? removed[0])) ?? null;
90
+ }
91
+
92
+ interface Planner {
93
+ domains: TenantDomainRecord[];
94
+ /** Live names held by OTHER tenants, among the names this call claims. */
95
+ takenElsewhere: Set<string>;
96
+ claimed: Set<string>;
97
+ targeted: Set<string>;
98
+ /** Domains a restore of this call targeted, whose one `verify` may follow (consumed by it). */
99
+ restored: Set<string>;
100
+ /**
101
+ * Live and ACTIVE domains a restore of this call found already back. The
102
+ * verify that follows is answered `unchanged`: a stale restore must never
103
+ * re-check, and so possibly take down, a domain that is serving.
104
+ */
105
+ servingAlready: Set<string>;
106
+ problems: TenantDomainProblem[];
107
+ steps: TenantDomainStep[];
108
+ entitled: boolean;
109
+ }
110
+
111
+ const fail = (planner: Planner, index: number, kind: TenantDomainProblemKind, hostname: string | null): void => {
112
+ planner.problems.push({ index, kind, hostname });
113
+ };
114
+
115
+ /** A name this tenant holds on a live domain. */
116
+ const heldHere = (planner: Planner, name: string) =>
117
+ planner.domains.some((domain) => isLive(domain) && namesOf(domain).includes(name));
118
+
119
+ /** The step of an add whose name the tenant already holds: unchanged, or the principal it asks for. */
120
+ function ownAdd(planner: Planner, index: number, own: TenantDomainRecord, principal: AddOperation['principal']): void {
121
+ if (planner.targeted.has(own.id)) return fail(planner, index, 'duplicateTarget', own.hostname);
122
+ planner.targeted.add(own.id);
123
+ const changes = principal !== undefined && principal !== own.principal && own.wwwHostname !== null;
124
+ planner.steps.push(changes ? { index, kind: 'principal', domain: own, principal } : { index, kind: 'noop', domain: own });
125
+ }
126
+
127
+ /** Why a new claim of `names` is refused, or null: twice in this call, another domain of this tenant, another tenant. */
128
+ function claimProblem(
129
+ planner: Planner,
130
+ host: string,
131
+ names: readonly string[],
132
+ ): { kind: 'duplicateTarget' | 'nameHeldHere' | 'nameTaken'; name: string } | null {
133
+ const twice = names.find((name) => planner.claimed.has(name));
134
+ if (twice !== undefined) return { kind: 'duplicateTarget', name: twice };
135
+ const mine = names.find((name) => heldHere(planner, name));
136
+ if (mine !== undefined) return { kind: 'nameHeldHere', name: mine };
137
+ const taken = guardedOf(host).find((name) => planner.takenElsewhere.has(name));
138
+ return taken === undefined ? null : { kind: 'nameTaken', name: taken };
139
+ }
140
+
141
+ function planAdd(planner: Planner, index: number, operation: AddOperation): void {
142
+ const host = hostnameOrNull(operation.hostname);
143
+ if (host === null) {
144
+ planner.problems.push({ index, kind: 'invalidHostname', hostname: null, input: operation.hostname });
145
+ return;
146
+ }
147
+ const names = claimOf(host);
148
+ if (operation.principal === 'www' && names.length === 1) return fail(planner, index, 'notAPair', host);
149
+ // Idempotent on the name: the tenant's own live domain answering on it is answered as it is.
150
+ const own = planner.domains.find((domain) => isLive(domain) && (domain.hostname === host || domain.wwwHostname === host));
151
+ if (own !== undefined) return ownAdd(planner, index, own, operation.principal);
152
+ const refused = claimProblem(planner, host, names);
153
+ if (refused !== null) return fail(planner, index, refused.kind, refused.name);
154
+ names.forEach((name) => planner.claimed.add(name));
155
+ planner.steps.push({ index, kind: 'add', hostname: host, names, principal: operation.principal ?? 'root' });
156
+ }
157
+
158
+ type TargetPlan = (planner: Planner, index: number, domain: TenantDomainRecord, operation: TargetOperation) => void;
159
+
160
+ /** An act only a live domain takes, or, for a `verify`, one this call restores before it. */
161
+ const liveOnly =
162
+ (then: TargetPlan): TargetPlan =>
163
+ (planner, index, domain, operation) =>
164
+ isLive(domain) || (operation.operation === 'verify' && planner.restored.has(domain.id))
165
+ ? then(planner, index, domain, operation)
166
+ : fail(planner, index, 'removed', domain.hostname);
167
+
168
+ const reasonOf = (operation: TargetOperation): string | null =>
169
+ 'reason' in operation ? (operation.reason ?? null) : null;
170
+
171
+ /** A restore takes its names back only while every one is still free, of every tenant, this one included. */
172
+ function busyNameOf(planner: Planner, domain: TenantDomainRecord): string | undefined {
173
+ return namesOf(domain)
174
+ .flatMap((name) => guardedOf(name).map((guarded) => ({ name, guarded })))
175
+ .find(
176
+ ({ name, guarded }) =>
177
+ planner.takenElsewhere.has(guarded) || heldHere(planner, name) || planner.claimed.has(name),
178
+ )?.guarded;
179
+ }
180
+
181
+ const TARGET_PLANS: Record<TargetOperation['operation'], TargetPlan> = {
182
+ verify: liveOnly((planner, index, domain) => {
183
+ if (planner.servingAlready.has(domain.id)) return void planner.steps.push({ index, kind: 'noop', domain });
184
+ return planner.entitled
185
+ ? void planner.steps.push({ index, kind: 'verify', domain })
186
+ : fail(planner, index, 'planRequired', domain.hostname);
187
+ }),
188
+ setPrincipal: liveOnly((planner, index, domain, operation) => {
189
+ if (domain.wwwHostname === null) return fail(planner, index, 'notAPair', domain.hostname);
190
+ const principal = (operation as Extract<TargetOperation, { operation: 'setPrincipal' }>).principal;
191
+ planner.steps.push(
192
+ domain.principal === principal ? { index, kind: 'noop', domain } : { index, kind: 'principal', domain, principal },
193
+ );
194
+ }),
195
+ archive: (planner, index, domain, operation) => {
196
+ planner.steps.push(
197
+ isLive(domain) ? { index, kind: 'archive', domain, reason: reasonOf(operation) } : { index, kind: 'noop', domain },
198
+ );
199
+ },
200
+ restore: (planner, index, domain, operation) => {
201
+ // Its verify may follow whatever this restore answers: `unchanged` on a live domain (a stale
202
+ // removed list, another tab), or a refusal that is the call's one real problem.
203
+ planner.restored.add(domain.id);
204
+ if (isLive(domain) && domain.status === 'ACTIVE') planner.servingAlready.add(domain.id);
205
+ if (isLive(domain)) return void planner.steps.push({ index, kind: 'noop', domain });
206
+ const busy = busyNameOf(planner, domain);
207
+ if (busy !== undefined) return fail(planner, index, 'nameNotFree', busy);
208
+ namesOf(domain).forEach((name) => planner.claimed.add(name));
209
+ planner.steps.push({ index, kind: 'restore', domain, reason: reasonOf(operation) });
210
+ },
211
+ };
212
+
213
+ function planTargeted(planner: Planner, index: number, operation: TargetOperation): void {
214
+ const domain = targetOf(planner.domains, operation);
215
+ if (domain === null) return fail(planner, index, 'notFound', operation.hostname ?? null);
216
+ // One entry per domain, but for the `verify` that may follow its `restore` (a restore button sends both).
217
+ const verifiesRestored = operation.operation === 'verify' && planner.restored.has(domain.id);
218
+ if (planner.targeted.has(domain.id) && !verifiesRestored) return fail(planner, index, 'duplicateTarget', domain.hostname);
219
+ planner.targeted.add(domain.id);
220
+ TARGET_PLANS[operation.operation](planner, index, domain, operation);
221
+ if (verifiesRestored) planner.restored.delete(domain.id);
222
+ }
223
+
224
+ /** Every name the call may claim (adds' and restores'), to ask who else holds it in ONE read. */
225
+ export function claimableNames(
226
+ operations: readonly TenantDomainOperation[],
227
+ domains: readonly TenantDomainRecord[],
228
+ ): string[] {
229
+ return operations.flatMap((operation) => {
230
+ if (operation.operation === 'add') {
231
+ const host = hostnameOrNull(operation.hostname);
232
+ return host === null ? [] : guardedOf(host);
233
+ }
234
+ const domain = operation.operation === 'restore' ? targetOf(domains, operation) : null;
235
+ return domain === null ? [] : namesOf(domain).flatMap((name) => guardedOf(name));
236
+ });
237
+ }
238
+
239
+ /** How many quota units the steps take: one per new claim and per restore. */
240
+ export const unitsOf = (steps: readonly TenantDomainStep[]): number =>
241
+ steps.filter((step) => step.kind === 'add' || step.kind === 'restore').length;
242
+
243
+ /** The names the steps claim: a new claim's and a restore's. */
244
+ export const claimsOf = (steps: readonly TenantDomainStep[]): string[] =>
245
+ steps.flatMap((step) => (step.kind === 'add' ? step.names : step.kind === 'restore' ? namesOf(step.domain) : []));
246
+
247
+ /**
248
+ * Check every operation; nothing is written. The steps in call order, or every
249
+ * problem. `takenElsewhere` is the live names OTHER tenants hold among
250
+ * {@link claimableNames}; `entitled` whether a `verify` may run at all.
251
+ */
252
+ export function planDomainOperations(input: {
253
+ operations: readonly TenantDomainOperation[];
254
+ domains: TenantDomainRecord[];
255
+ takenElsewhere: ReadonlySet<string>;
256
+ entitled: boolean;
257
+ }): { steps: TenantDomainStep[]; problems: TenantDomainProblem[] } {
258
+ const planner: Planner = {
259
+ domains: input.domains,
260
+ takenElsewhere: new Set(input.takenElsewhere),
261
+ claimed: new Set(),
262
+ targeted: new Set(),
263
+ restored: new Set(),
264
+ servingAlready: new Set(),
265
+ problems: [],
266
+ steps: [],
267
+ entitled: input.entitled,
268
+ };
269
+ input.operations.forEach((operation, index) =>
270
+ operation.operation === 'add' ? planAdd(planner, index, operation) : planTargeted(planner, index, operation),
271
+ );
272
+ return planner.problems.length > 0 ? { steps: [], problems: planner.problems } : { steps: planner.steps, problems: [] };
273
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The ports a host gives custom domains. The domain table is the HOST's: the
3
+ * package maps no table and names no column, so every read and write goes
4
+ * through {@link TenantDomainPort}, and the plan's quota through
5
+ * {@link TenantDomainQuota}. Both are required, every member.
6
+ */
7
+ import type { TenantDomainRecord, TenantDomainRow } from './record';
8
+
9
+ /**
10
+ * The host's domain rows. Statement budget (ADOPTING.md, "Custom domains"):
11
+ * `rows` and `holders` are ONE read each; a member that adds a read is a defect.
12
+ */
13
+ export interface TenantDomainPort<Tx = unknown> {
14
+ /** EVERY row of the tenant, removed ones included, newest first (`createdAt` desc, `hostname` asc). One read. */
15
+ rows(tenantId: string, tx?: Tx): Promise<TenantDomainRow[]>;
16
+ /** The live rows of ANY tenant holding any of `hostnames`. One read. */
17
+ holders(hostnames: readonly string[], tx?: Tx): Promise<{ hostname: string; tenantId: string }[]>;
18
+ /** Run `work` in ONE transaction at SERIALIZABLE isolation. */
19
+ transaction<T>(work: (tx: Tx) => Promise<T>): Promise<T>;
20
+ /**
21
+ * What a thrown error means: `'retry'` a serializable transaction that lost
22
+ * to a concurrent one (nothing was written), `'taken'` a unique-index
23
+ * violation on a hostname (a race claimed it first), `null` anything else,
24
+ * which the engine rethrows.
25
+ */
26
+ failure(error: unknown): 'retry' | 'taken' | null;
27
+ /**
28
+ * Write a claim's rows: the name, and for a zone apex its `www.` too (one
29
+ * domain, ONE token, which the host mints and which must be unguessable).
30
+ */
31
+ claim(tx: Tx, tenantId: string, hostname: string, principal: 'root' | 'www'): Promise<TenantDomainRecord>;
32
+ /** Make `principal` the pair's principal address. */
33
+ setPrincipal(tx: Tx, tenantId: string, id: string, principal: 'root' | 'www'): Promise<void>;
34
+ /**
35
+ * Record a check on every name of the domain, by each name's row id: verified
36
+ * moves the rows to ACTIVE, else FAILED; a `null` pointing answer leaves the
37
+ * stored one as it is.
38
+ */
39
+ recordCheck(
40
+ tx: Tx,
41
+ tenantId: string,
42
+ domain: TenantDomainRecord,
43
+ outcome: { verified: boolean; pointsHere: Readonly<Record<string, boolean | null>> },
44
+ at: Date,
45
+ ): Promise<void>;
46
+ /**
47
+ * Remove the pair (root and `www.`): archived, AND made unservable, so a
48
+ * release that cannot read the archive column (a rollback) still never serves it.
49
+ */
50
+ archive(tx: Tx, tenantId: string, id: string, at: Date, by: string | null): Promise<void>;
51
+ /** Bring the pair back, unverified: ownership is proven again with the same token. */
52
+ restore(tx: Tx, tenantId: string, id: string): Promise<void>;
53
+ /** One audit line per removal and restore, in the host's own ids and words. */
54
+ audit(
55
+ tx: Tx,
56
+ line: { act: 'archive' | 'restore'; tenantId: string; domain: TenantDomainRecord; reason: string | null; via: string },
57
+ ): Promise<void>;
58
+ }
59
+
60
+ export const TENANT_DOMAIN_PORT_METHODS = [
61
+ 'rows',
62
+ 'holders',
63
+ 'transaction',
64
+ 'failure',
65
+ 'claim',
66
+ 'setPrincipal',
67
+ 'recordCheck',
68
+ 'archive',
69
+ 'restore',
70
+ 'audit',
71
+ ] as const satisfies readonly (keyof TenantDomainPort)[];
72
+
73
+ /**
74
+ * The host's plan for custom domains. `via` is whatever the host put on the
75
+ * context (where the call came from); the package never reads it, so a host
76
+ * that answers one caller with its own refusal (a thrown platform error) and
77
+ * another with a problem decides that here.
78
+ */
79
+ export interface TenantDomainQuota<Tx = unknown> {
80
+ /** Whether a `verify` may run at all. Asked only when the call has one; may throw the host's own refusal. */
81
+ mayVerify(tenantId: string, via: string): Promise<boolean>;
82
+ /**
83
+ * Reserve `units` (> 0) new domains: the limit to re-check in the
84
+ * transaction (`null` = unlimited), or which refusal. May throw the host's own.
85
+ */
86
+ reserve(
87
+ tenantId: string,
88
+ units: number,
89
+ via: string,
90
+ ): Promise<{ limit: number | null } | { refused: 'planRequired' | 'planLimit' }>;
91
+ /** The tenant's domains counted against the plan, re-read on `tx`. */
92
+ used(tenantId: string, tx: Tx): Promise<number>;
93
+ }
94
+
95
+ export const TENANT_DOMAIN_QUOTA_METHODS = ['mayVerify', 'reserve', 'used'] as const satisfies readonly (keyof TenantDomainQuota)[];
96
+
97
+ /** How the host resolves names. Its own, so its tests can replace it. */
98
+ export interface TenantDomainResolver {
99
+ /** TXT records, each as its chunks. */
100
+ txt(name: string): Promise<string[][]>;
101
+ ipv4(name: string): Promise<string[]>;
102
+ ipv6(name: string): Promise<string[]>;
103
+ }
104
+
105
+ export const TENANT_DOMAIN_RESOLVER_METHODS = ['txt', 'ipv4', 'ipv6'] as const satisfies readonly (keyof TenantDomainResolver)[];
@@ -0,0 +1,216 @@
1
+ /**
2
+ * The claims already made: each one's state, the records it still needs, and
3
+ * verify / remove, or, with none yet, the address to have ready; then the
4
+ * removed list. The flow the screen has to make obvious: claim a hostname,
5
+ * publish the TXT record shown, point the domain here, verify. A domain does
6
+ * NOT serve until the TXT check passes, because pointing DNS proves nothing
7
+ * about ownership. BOTH halves are on screen: ownership and pointing are
8
+ * independent, and a green status over a dead site is worse than a red one.
9
+ *
10
+ * The writes are the host's (its API, its keyed mutation, its refusal words);
11
+ * the card only routes each refusal to where it is told.
12
+ */
13
+ import { useCallback, useState, type JSX, type ReactNode } from 'react';
14
+
15
+ import { Alert } from '@12-apps/ui/data-display/Alert';
16
+ import { EmptyState } from '@12-apps/ui/data-display/EmptyState';
17
+ import { Box } from '@12-apps/ui/mui/Box';
18
+ import { Stack } from '@12-apps/ui/mui/Stack';
19
+ import { Text } from '@12-apps/ui/typography/Text';
20
+
21
+ import { DomainsScreenProvider, useDomainsScreen, type TenantDomainItem, type TenantDomainsComponents } from './context';
22
+ import type { TenantDomainPairCopy, TenantDomainsCopy } from './copy';
23
+ import { PointingRecord, domainName } from './records';
24
+ import { RemovedList } from './removed';
25
+ import { DomainRow, type RowRefusalState } from './row';
26
+
27
+ /** One write on one domain. `settled` answers after the host's re-read: a restore reveals its row. */
28
+ export type TenantDomainWrite<D extends TenantDomainItem> =
29
+ | { kind: 'verify'; domain: D }
30
+ | { kind: 'restore'; domain: D; settled?: (refusal: string | null) => void }
31
+ | { kind: 'principal'; domain: D; principal: 'root' | 'www' };
32
+
33
+ /** A standing refusal of one domain's write, with the write that was refused. */
34
+ export interface TenantDomainRefusal<D extends TenantDomainItem> {
35
+ key: string;
36
+ message: string;
37
+ input: { kind: 'verify' | 'restore' | 'principal' | 'remove'; domain: D };
38
+ }
39
+
40
+ /** The host's writes, ONE PER DOMAIN: their state, a write, and the confirm-gated remove (it rejects with the refusal). */
41
+ export interface TenantDomainWrites<D extends TenantDomainItem> {
42
+ writes: {
43
+ errors: readonly TenantDomainRefusal<D>[];
44
+ isPending(id: string): boolean;
45
+ dismiss(id: string): void;
46
+ };
47
+ run(write: TenantDomainWrite<D>): void;
48
+ remove(domain: D): Promise<void>;
49
+ }
50
+
51
+ export interface DomainsCardProps<D extends TenantDomainItem> {
52
+ domains: D[];
53
+ /** The removed (archived) domains. */
54
+ removed: D[];
55
+ dnsTargets: string[];
56
+ disabled: boolean;
57
+ /** The resolved pack for this render. */
58
+ copy: TenantDomainsCopy;
59
+ writes: TenantDomainWrites<D>;
60
+ /**
61
+ * The host's own empty state, drawn in place of the package's (an
62
+ * `EmptyState` titled `records.emptyTitle`, test id `domains-empty`) when
63
+ * there is no domain yet: for a host whose tooling reads its own JSX, such
64
+ * as a search index that files the card under its test id.
65
+ */
66
+ emptyState?: ReactNode;
67
+ }
68
+
69
+ /** No domain yet: the invitation, and the address to have ready. */
70
+ function NoDomainsYet({ dnsTargets, emptyState }: { dnsTargets: string[]; emptyState?: ReactNode }): JSX.Element {
71
+ const records = useDomainsScreen().copy.records;
72
+ return (
73
+ <>
74
+ {/* An invitation rather than a statement of absence: the state a tenant
75
+ is in when it arrives on this screen for the first time. */}
76
+ {emptyState ?? (
77
+ <EmptyState variant="minimal" title={records.emptyTitle} description={records.emptyBody} dataTestId="domains-empty" />
78
+ )}
79
+ {/* Unnumbered: with no domain there is no TXT record yet, so this is not
80
+ step 2 of anything; it is the address to have ready. */}
81
+ <PointingRecord dnsTargets={dnsTargets} numbered={false} copy={records} />
82
+ </>
83
+ );
84
+ }
85
+
86
+ /** A refused restore's sentence for this removed domain, or null. */
87
+ function restoreRefusalOf<D extends TenantDomainItem>(errors: readonly TenantDomainRefusal<D>[], domain: D): string | null {
88
+ return errors.find((refusal) => refusal.key === domain.id && refusal.input.kind === 'restore')?.message ?? null;
89
+ }
90
+
91
+ /** A live row's own refused write, told in that row. The first refusal on screen is `domains-error`. */
92
+ function rowRefusalOf<D extends TenantDomainItem>(writes: TenantDomainWrites<D>['writes'], domain: D): RowRefusalState | null {
93
+ const told = writes.errors.filter((refusal) => refusal.input.kind !== 'restore');
94
+ const at = told.findIndex((refusal) => refusal.key === domain.id);
95
+ const refusal = told[at];
96
+ if (refusal === undefined) return null;
97
+ return {
98
+ kind: refusal.input.kind === 'principal' ? 'principal' : 'other',
99
+ message: refusal.message,
100
+ testId: at === 0 ? 'domains-error' : `domains-error-${refusal.key}`,
101
+ onDismiss: () => writes.dismiss(refusal.key),
102
+ };
103
+ }
104
+
105
+ function CardBody<D extends TenantDomainItem>({
106
+ domains,
107
+ removed,
108
+ dnsTargets,
109
+ disabled,
110
+ writes: host,
111
+ emptyState,
112
+ }: DomainsCardProps<D>): JSX.Element {
113
+ const { copy } = useDomainsScreen();
114
+ const { writes, run, remove } = host;
115
+ const [revealed, setRevealed] = useState<string | null>(null);
116
+ const doneRevealing = useCallback(() => setRevealed(null), []);
117
+ // Each refusal is told in its own row; only one whose domain has left the
118
+ // list meanwhile is told at the head, named after it.
119
+ const live = new Set(domains.map((domain) => domain.id));
120
+ const headRefusals = writes.errors.filter((refusal) => refusal.input.kind !== 'restore' && !live.has(refusal.key));
121
+
122
+ return (
123
+ <Stack spacing={2} data-testid="domains-card">
124
+ {headRefusals.map((refusal) => (
125
+ <Alert
126
+ key={refusal.key}
127
+ variant="danger"
128
+ // Named after its domain: two rows can be refused at once.
129
+ title={domainName(refusal.input.domain, copy.pair)}
130
+ description={refusal.message}
131
+ closable
132
+ closeLabel={copy.closeAlert}
133
+ onClose={() => writes.dismiss(refusal.key)}
134
+ data-testid={
135
+ writes.errors.find((told) => told.input.kind !== 'restore')?.key === refusal.key
136
+ ? 'domains-error'
137
+ : `domains-error-${refusal.key}`
138
+ }
139
+ />
140
+ ))}
141
+
142
+ {domains.length === 0 ? (
143
+ <NoDomainsYet dnsTargets={dnsTargets} emptyState={emptyState} />
144
+ ) : (
145
+ domains.map((domain) => (
146
+ <DomainRow
147
+ key={domain.id}
148
+ domain={domain}
149
+ dnsTargets={dnsTargets}
150
+ disabled={disabled}
151
+ busy={writes.isPending(domain.id)}
152
+ refusal={rowRefusalOf(writes, domain)}
153
+ reveal={revealed === domain.id}
154
+ onRevealed={doneRevealing}
155
+ onVerify={() => run({ kind: 'verify', domain })}
156
+ onPrincipal={(principal) => run({ kind: 'principal', domain, principal })}
157
+ onRemove={() => remove(domain)}
158
+ />
159
+ ))
160
+ )}
161
+
162
+ <RemovedList
163
+ removed={removed}
164
+ isBusy={(domain) => disabled || writes.isPending(domain.id)}
165
+ refusalOf={(domain) => restoreRefusalOf(writes.errors, domain)}
166
+ onDismissRefusal={(domain) => writes.dismiss(domain.id)}
167
+ onRestore={(domain) =>
168
+ run({ kind: 'restore', domain, settled: (refusal) => refusal === null && setRevealed(domain.id) })
169
+ }
170
+ />
171
+ </Stack>
172
+ );
173
+ }
174
+
175
+ /** The card, its pack and the host's widgets provided to every part. */
176
+ export function makeDomainsCard(components: TenantDomainsComponents) {
177
+ return function DomainsCard<D extends TenantDomainItem>(props: DomainsCardProps<D>): JSX.Element {
178
+ return (
179
+ <DomainsScreenProvider value={{ copy: props.copy, components }}>
180
+ <CardBody {...props} />
181
+ </DomainsScreenProvider>
182
+ );
183
+ };
184
+ }
185
+
186
+ /** Under the claim field, before saving, when the typed address is a root domain: it is claimed with its `www.`. */
187
+ export function PairAnnouncement({
188
+ root,
189
+ www,
190
+ copy,
191
+ }: {
192
+ root: string;
193
+ www: string;
194
+ copy: Pick<TenantDomainPairCopy, 'pairAnnouncement'>;
195
+ }): JSX.Element {
196
+ const words = copy.pairAnnouncement(root, www);
197
+ const strong = (text: string) => (
198
+ <Text as="span" variant="body" size="sm" weight="semibold">
199
+ {text}
200
+ </Text>
201
+ );
202
+ return (
203
+ <Box
204
+ sx={{ bgcolor: 'action.hover', borderRadius: 1, px: 1.5, py: 1.25, maxWidth: '40rem' }}
205
+ data-testid="domain-pair-announcement"
206
+ >
207
+ <Text variant="body" size="sm" style={{ overflowWrap: 'anywhere' }}>
208
+ {words.before}
209
+ {strong(root)}
210
+ {words.and}
211
+ {strong(www)}
212
+ {words.after}
213
+ </Text>
214
+ </Box>
215
+ );
216
+ }