Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

scopedSettings.ts

435 lines16.5 KB

1import {
2 ClientSettingsSchema,
3 type ClientSettingsPatch,
4 type EnvironmentId,
5 isNullableProjectSettingsOverride,
6 PROJECT_SCOPED_SERVER_SETTING_KEYS,
7 type ProjectId,
8 type ProjectScopedServerSettingKey,
9 type ProjectSettingsOverrides,
10 ServerSettings,
11 type T3ProjectFile,
12 type ServerSettingsPatch,
13} from "@t3tools/contracts";
14import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
15import {
16 clearProjectSettingsOverrides,
17 resolveProjectSettings,
18 resolveWorktreeCleanup,
19 type ProjectSettingSource,
20} from "@t3tools/shared/projectSettings";
21import * as Equal from "effect/Equal";
22import * as Cause from "effect/Cause";
23​
24import type { ResolvedSettingsScope } from "./settingsScope";
25​
26export type ScopedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
27​
28interface ScopedSettingsEnvironment {
29 readonly environmentId: EnvironmentId;
30 readonly label: string;
31 readonly connection: { readonly phase: EnvironmentConnectionPhase };
32 readonly serverConfig: {
33 readonly settings: ServerSettings;
34 readonly environment?: {
35 readonly capabilities: { readonly projectSettingsOverrides?: boolean | undefined };
36 };
37 } | null;
39​
40const SERVER_KEYS = new Set<string>(Object.keys(ServerSettings.fields));
41const CLIENT_KEYS = new Set<string>(Object.keys(ClientSettingsSchema.fields));
42const PROJECT_SCOPED_KEYS = new Set<string>(PROJECT_SCOPED_SERVER_SETTING_KEYS);
43​
44export function isProjectScopedSettingKey(key: string): key is ProjectScopedServerSettingKey {
45 return PROJECT_SCOPED_KEYS.has(key);
47​
48function isPlainObject(value: unknown): value is Record<string, unknown> {
49 return typeof value === "object" && value !== null && !Array.isArray(value);
51​
52/** The representative supplies display values, never the set of write targets. */
53export function selectScopedSettingsEnvironments<T extends ScopedSettingsEnvironment>(
54 scope: ResolvedSettingsScope,
55 available: readonly T[],
56 primaryEnvironmentId: EnvironmentId | null,
57) {
58 const selectedIds = new Set(scope.environmentIds);
59 const environments = available.filter((environment) =>
60 selectedIds.has(environment.environmentId),
61 );
62 const connectedEnvironments = environments.filter(
63 (environment) =>
64 environment.connection.phase === "connected" && environment.serverConfig !== null,
65 );
66 const environment =
67 connectedEnvironments.find((candidate) => candidate.environmentId === primaryEnvironmentId) ??
68 connectedEnvironments[0] ??
69 null;
70 return { environments, connectedEnvironments, environment };
72​
73/**
74 * One (environment, project) pair the scope writes to, with that project's
75 * effective settings. Environment scopes have no member and read the
76 * environment settings directly.
77 */
78export interface ScopedSettingsTarget {
79 readonly environmentId: EnvironmentId;
80 /** The environment's label; a project is the same project on every environment. */
81 readonly label: string;
82 readonly projectId: ProjectId | null;
83 readonly settings: ServerSettings;
84 readonly sources: Readonly<Record<ProjectScopedServerSettingKey, ProjectSettingSource>>;
86​
87/** Effective settings per connected target: members at project scope, environments otherwise. */
88export function resolveScopedSettingsTargets(
89 scope: ResolvedSettingsScope,
90 connectedEnvironments: readonly ScopedSettingsEnvironment[],
91 // Each member's decoded t3.json, keyed by physical project key, once read.
92 // A member absent here has no file tier yet; null is a missing or invalid file.
93 projectFiles?: ReadonlyMap<string, T3ProjectFile | null>,
94): readonly ScopedSettingsTarget[] {
95 const byId = new Map(
96 connectedEnvironments.map((environment) => [environment.environmentId, environment]),
97 );
98 if (scope.kind === "project" || scope.kind === "checkout") {
99 return scope.members.flatMap((member) => {
100 const environment = byId.get(member.environmentId);
101 if (!environment?.serverConfig) return [];
102 const projectFile = projectFiles?.get(member.physicalProjectKey);
103 const resolved =
104 projectFile === undefined
105 ? resolveProjectSettings(environment.serverConfig.settings, member.id)
106 : resolveProjectSettings(environment.serverConfig.settings, member.id, null, projectFile);
107 return [
108 {
109 environmentId: member.environmentId,
110 label: environment.label,
111 projectId: member.id,
112 settings: resolved.settings,
113 sources: resolved.sources,
114 },
115 ];
116 });
117 }
118 return connectedEnvironments.flatMap((environment) =>
119 environment.serverConfig
120 ? [
121 {
122 environmentId: environment.environmentId,
123 label: environment.label,
124 projectId: null,
125 settings: environment.serverConfig.settings,
126 sources: resolveProjectSettings(environment.serverConfig.settings, null).sources,
127 },
128 ]
129 : [],
130 );
132​
133export function scopedSettingsAreMixed(
134 targets: readonly Pick<ScopedSettingsTarget, "settings">[],
135 keys: readonly (keyof ServerSettings)[],
136): boolean {
137 const first = targets[0];
138 return (
139 first !== undefined &&
140 targets.some((candidate) =>
141 keys.some((key) => !Equal.equals(first.settings[key], candidate.settings[key])),
142 )
143 );
145​
146export type ScopedSettingSource = ProjectSettingSource | "mixed";
147​
148/** Whether the keys are overridden on every target, inherited on every target, or split. */
149export function scopedSettingsSource(
150 targets: readonly Pick<ScopedSettingsTarget, "sources">[],
151 keys: readonly (keyof ServerSettings)[],
152): ScopedSettingSource {
153 const scoped = keys.filter(isProjectScopedSettingKey);
154 if (scoped.length === 0 || targets.length === 0) return "environment";
155 const sources = new Set(targets.flatMap((target) => scoped.map((key) => target.sources[key])));
156 return sources.size > 1
157 ? "mixed"
158 : sources.has("project")
159 ? "project"
160 : sources.has("t3.json")
161 ? "t3.json"
162 : "environment";
164​
165interface ScopedServerWrite {
166 readonly environmentId: EnvironmentId;
167 readonly label: string;
168 readonly patch: ServerSettingsPatch;
170​
171function projectOverrideWrites(
172 scope: Extract<ResolvedSettingsScope, { kind: "project" | "checkout" }>,
173 environments: readonly ScopedSettingsEnvironment[],
174 update: (
175 current: ProjectSettingsOverrides,
176 settings: ServerSettings,
177 projectId: ProjectId,
178 ) => ProjectSettingsOverrides | null,
179): ScopedServerWrite[] {
180 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
181 const writes = new Map<EnvironmentId, ScopedServerWrite>();
182 for (const member of scope.members) {
183 const environment = byId.get(member.environmentId);
184 if (
185 !environment?.serverConfig ||
186 environment.connection.phase !== "connected" ||
187 environment.serverConfig.environment?.capabilities.projectSettingsOverrides !== true
188 ) {
189 continue;
190 }
191 const settings = environment.serverConfig.settings;
192 const entry = update(settings.projectSettingsOverrides[member.id] ?? {}, settings, member.id);
193 const existing = writes.get(member.environmentId);
194 writes.set(member.environmentId, {
195 environmentId: member.environmentId,
196 label: environment.label,
197 patch: {
198 projectSettingsOverrides: {
199 ...existing?.patch.projectSettingsOverrides,
200 [member.id]: entry,
201 },
202 },
203 });
204 }
205 return [...writes.values()];
207​
208/**
209 * Environment scopes write the patch to every connected environment; project
210 * and checkout scopes write the scopable keys into each member's override
211 * entry on its environment. Client keys always persist locally.
212 */
213export function planScopedSettingsPatch(
214 scope: ResolvedSettingsScope,
215 environments: readonly ScopedSettingsEnvironment[],
216 patch: ScopedSettingsPatch,
217) {
218 const clientPatch = Object.fromEntries(
219 Object.entries(patch).filter(([key]) => CLIENT_KEYS.has(key) && !SERVER_KEYS.has(key)),
220 ) as ClientSettingsPatch;
221 const serverPatch = Object.fromEntries(
222 Object.entries(patch).filter(([key]) => SERVER_KEYS.has(key)),
223 ) as ServerSettingsPatch;
224 const serverKeys = Object.keys(serverPatch);
225 const { connectedEnvironments } = selectScopedSettingsEnvironments(scope, environments, null);
226 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
227 const unscopableKeys = isProjectScope
228 ? serverKeys.filter((key) => !isProjectScopedSettingKey(key))
229 : [];
230 const serverWrites: ScopedServerWrite[] =
231 serverKeys.length === 0
232 ? []
233 : isProjectScope
234 ? unscopableKeys.length > 0
235 ? []
236 : projectOverrideWrites(scope, environments, (current, settings, projectId) => {
237 // Object-valued keys arrive as partial patches (the writing style
238 // rows send one field); an override entry stores the whole value,
239 // so complete the patch from the target's effective value.
240 const effective = resolveProjectSettings(settings, projectId).settings;
241 const next: Record<string, unknown> = { ...current };
242 for (const [key, value] of Object.entries(serverPatch)) {
243 if (key === "worktreeCleanup" && serverPatch.worktreeCleanup?.mode === "custom") {
244 next[key] = {
245 mode: "custom",
246 rules: {
247 ...resolveWorktreeCleanup(settings, projectId),
248 ...serverPatch.worktreeCleanup.rules,
249 },
250 };
251 continue;
252 }
253 // A picker's "Inherit" sends null; for keys whose override
254 // cannot store null that means remove the override.
255 if (
256 value === null &&
257 !isNullableProjectSettingsOverride(key as ProjectScopedServerSettingKey)
258 ) {
259 delete next[key];
260 continue;
261 }
262 const base = effective[key as keyof ServerSettings];
263 next[key] =
264 isPlainObject(value) && isPlainObject(base) ? { ...base, ...value } : value;
265 }
266 return next as ProjectSettingsOverrides;
267 })
268 : scope.kind === "all" || scope.kind === "environment"
269 ? connectedEnvironments.map((environment) => ({
270 environmentId: environment.environmentId,
271 label: environment.label,
272 patch:
273 environment.serverConfig?.settings.worktreeCleanup != null &&
274 serverPatch.storageCleanup &&
275 Object.keys(serverPatch.storageCleanup).some((key) => key.startsWith("worktree"))
276 ? {
277 ...serverPatch,
278 worktreeCleanup: {
279 mode: "custom",
280 rules: {
281 ...resolveWorktreeCleanup(environment.serverConfig.settings, null),
282 ...Object.fromEntries(
283 Object.entries(serverPatch.storageCleanup).filter(([key]) =>
284 key.startsWith("worktree"),
285 ),
286 ),
287 },
288 },
289 }
290 : serverPatch,
291 }))
292 : [];
293 const hasClientWrite = Object.keys(clientPatch).length > 0;
294 const hasWrite = hasClientWrite || serverWrites.length > 0;
295 const unavailableReason =
296 hasWrite || Object.keys(patch).length === 0
297 ? null
298 : scope.kind === "unavailable"
299 ? scope.message
300 : unscopableKeys.length > 0
301 ? "This setting is environment-wide and cannot be overridden by a project."
302 : isProjectScope
303 ? "Connect the selected checkouts, or update their environments, to save a project override."
304 : `Connect ${scope.kind === "environment" ? scope.label : "an environment"} to save this setting.`;
305 return { clientPatch, hasClientWrite, serverWrites, unavailableReason };
307​
308/** Remove the keys' project overrides so each member inherits its environment value again. */
309export function planScopedSettingsClear(
310 scope: ResolvedSettingsScope,
311 environments: readonly ScopedSettingsEnvironment[],
312 keys: readonly ProjectScopedServerSettingKey[],
313) {
314 const serverWrites =
315 scope.kind === "project" || scope.kind === "checkout"
316 ? projectOverrideWrites(scope, environments, (_current, settings, projectId) =>
317 clearProjectSettingsOverrides(settings, projectId, keys),
318 )
319 : [];
320 return {
321 clientPatch: {} as ClientSettingsPatch,
322 hasClientWrite: false,
323 serverWrites,
324 unavailableReason:
325 serverWrites.length > 0
326 ? null
327 : "Connect the selected checkouts, or update their environments, to reset this override.",
328 };
330​
331export interface ProjectOverrideEntry {
332 readonly environmentId: EnvironmentId;
333 readonly projectId: ProjectId;
335​
336/**
337 * The projects on the selected environments that override `keys`. An
338 * environment edit leaves these untouched, so the row can name them and
339 * offer to clear them.
340 */
341export function listProjectOverrides(
342 environments: readonly ScopedSettingsEnvironment[],
343 keys: readonly (keyof ServerSettings)[],
344): readonly ProjectOverrideEntry[] {
345 const scoped = keys.filter(isProjectScopedSettingKey);
346 if (scoped.length === 0) return [];
347 return environments.flatMap((environment) => {
348 const overrides = environment.serverConfig?.settings.projectSettingsOverrides;
349 if (!overrides) return [];
350 return Object.entries(overrides).flatMap(([projectId, entry]) =>
351 scoped.some((key) => Object.hasOwn(entry, key))
352 ? [{ environmentId: environment.environmentId, projectId: projectId as ProjectId }]
353 : [],
354 );
355 });
357​
358/** Drop `keys` from the named project entries so they follow the environment again. */
359export function planProjectOverridesClear(
360 environments: readonly ScopedSettingsEnvironment[],
361 entries: readonly ProjectOverrideEntry[],
362 keys: readonly ProjectScopedServerSettingKey[],
363) {
364 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
365 const writes = new Map<EnvironmentId, ScopedServerWrite>();
366 for (const { environmentId, projectId } of entries) {
367 const environment = byId.get(environmentId);
368 if (!environment?.serverConfig || environment.connection.phase !== "connected") continue;
369 const settings = environment.serverConfig.settings;
370 const existing = writes.get(environmentId);
371 writes.set(environmentId, {
372 environmentId,
373 label: environment.label,
374 patch: {
375 projectSettingsOverrides: {
376 ...existing?.patch.projectSettingsOverrides,
377 [projectId]: clearProjectSettingsOverrides(settings, projectId, keys),
378 },
379 },
380 });
381 }
382 const serverWrites = [...writes.values()];
383 return {
384 clientPatch: {} as ClientSettingsPatch,
385 hasClientWrite: false,
386 serverWrites,
387 unavailableReason:
388 serverWrites.length > 0 ? null : "Connect the environments to reset these overrides.",
389 };
391​
392/** Wait for every target so a failed environment does not hide successful or later writes. */
393export async function persistScopedSettingsPatch(
394 plan: ReturnType<typeof planScopedSettingsPatch>,
395 persistServer: (input: {
396 environmentId: EnvironmentId;
397 input: { patch: ServerSettingsPatch };
398 }) => Promise<{ readonly _tag: "Success" | "Failure"; readonly cause?: Cause.Cause<unknown> }>,
399 persistClient: (patch: ClientSettingsPatch) => void,
400) {
401 if (plan.hasClientWrite) persistClient(plan.clientPatch);
402 const results = await Promise.allSettled(
403 plan.serverWrites.map(({ environmentId, patch }) =>
404 persistServer({ environmentId, input: { patch } }),
405 ),
406 );
407 const failedEnvironments = plan.serverWrites.flatMap((environment, index) => {
408 const result = results[index];
409 if (result?.status === "fulfilled" && result.value._tag === "Success") return [];
410 const error: unknown =
411 result?.status === "rejected"
412 ? result.reason
413 : result?.status === "fulfilled" && result.value.cause
414 ? Cause.squash(result.value.cause)
415 : undefined;
416 return [
417 {
418 ...environment,
419 message:
420 error instanceof Error
421 ? error.message
422 : "The save failed. Try reconnecting and saving again.",
423 },
424 ];
425 });
426 const savedEnvironments = plan.serverWrites.filter((_, index) => {
427 const result = results[index];
428 return result?.status === "fulfilled" && result.value._tag === "Success";
429 });
430 return {
431 failedEnvironments,
432 savedEnvironments,
433 savedEnvironmentCount: savedEnvironments.length,
434 };