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

scopedSettings.ts

475 lines17.2 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​
73export interface ScopedSettingsTarget {
74 readonly environmentId: EnvironmentId;
75 readonly label: string;
76 readonly projectId: ProjectId | null;
77 readonly settings: ServerSettings;
78 readonly sources: Readonly<Record<ProjectScopedServerSettingKey, ProjectSettingSource>>;
80​
81export function resolveScopedSettingsTargets(
82 scope: ResolvedSettingsScope,
83 connectedEnvironments: readonly ScopedSettingsEnvironment[],
84 // A member absent here has no file tier yet; null is a missing or invalid file.
85 projectFiles?: ReadonlyMap<string, T3ProjectFile | null>,
86): readonly ScopedSettingsTarget[] {
87 const byId = new Map(
88 connectedEnvironments.map((environment) => [environment.environmentId, environment]),
89 );
90 if (scope.kind === "project" || scope.kind === "checkout") {
91 return scope.members.flatMap((member) => {
92 const environment = byId.get(member.environmentId);
93 if (!environment?.serverConfig) return [];
94 const projectFile = projectFiles?.get(member.physicalProjectKey);
95 const resolved =
96 projectFile === undefined
97 ? resolveProjectSettings(environment.serverConfig.settings, member.id)
98 : resolveProjectSettings(environment.serverConfig.settings, member.id, null, projectFile);
99 return [
100 {
101 environmentId: member.environmentId,
102 label: environment.label,
103 projectId: member.id,
104 settings: resolved.settings,
105 sources: resolved.sources,
106 },
107 ];
108 });
109 }
110 return connectedEnvironments.flatMap((environment) =>
111 environment.serverConfig
112 ? [
113 {
114 environmentId: environment.environmentId,
115 label: environment.label,
116 projectId: null,
117 settings: environment.serverConfig.settings,
118 sources: resolveProjectSettings(environment.serverConfig.settings, null).sources,
119 },
120 ]
121 : [],
122 );
124​
125export function scopedSettingsAreMixed(
126 targets: readonly Pick<ScopedSettingsTarget, "settings">[],
127 keys: readonly (keyof ServerSettings)[],
128): boolean {
129 const first = targets[0];
130 return (
131 first !== undefined &&
132 targets.some((candidate) =>
133 keys.some((key) => !Equal.equals(first.settings[key], candidate.settings[key])),
134 )
135 );
137​
138export type ScopedSettingSource = ProjectSettingSource | "mixed";
139​
140export function scopedSettingsSource(
141 targets: readonly Pick<ScopedSettingsTarget, "sources">[],
142 keys: readonly (keyof ServerSettings)[],
143): ScopedSettingSource {
144 const scoped = keys.filter(isProjectScopedSettingKey);
145 if (scoped.length === 0 || targets.length === 0) return "environment";
146 const sources = new Set(targets.flatMap((target) => scoped.map((key) => target.sources[key])));
147 return sources.size > 1
148 ? "mixed"
149 : sources.has("project")
150 ? "project"
151 : sources.has("t3.json")
152 ? "t3.json"
153 : "environment";
155​
156interface ScopedServerWrite {
157 readonly environmentId: EnvironmentId;
158 readonly label: string;
159 readonly patch: ServerSettingsPatch;
160 readonly previous: ServerSettings;
162​
163function projectOverrideWrites(
164 scope: Extract<ResolvedSettingsScope, { kind: "project" | "checkout" }>,
165 environments: readonly ScopedSettingsEnvironment[],
166 update: (
167 current: ProjectSettingsOverrides,
168 settings: ServerSettings,
169 projectId: ProjectId,
170 ) => ProjectSettingsOverrides | null,
171): ScopedServerWrite[] {
172 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
173 const writes = new Map<EnvironmentId, ScopedServerWrite>();
174 for (const member of scope.members) {
175 const environment = byId.get(member.environmentId);
176 if (
177 !environment?.serverConfig ||
178 environment.connection.phase !== "connected" ||
179 environment.serverConfig.environment?.capabilities.projectSettingsOverrides !== true
180 ) {
181 continue;
182 }
183 const settings = environment.serverConfig.settings;
184 const entry = update(settings.projectSettingsOverrides[member.id] ?? {}, settings, member.id);
185 const existing = writes.get(member.environmentId);
186 writes.set(member.environmentId, {
187 environmentId: member.environmentId,
188 label: environment.label,
189 previous: settings,
190 patch: {
191 projectSettingsOverrides: {
192 ...existing?.patch.projectSettingsOverrides,
193 [member.id]: entry,
194 },
195 },
196 });
197 }
198 return [...writes.values()];
200​
201export function planScopedSettingsPatch(
202 scope: ResolvedSettingsScope,
203 environments: readonly ScopedSettingsEnvironment[],
204 patch: ScopedSettingsPatch,
205) {
206 const clientPatch = Object.fromEntries(
207 Object.entries(patch).filter(([key]) => CLIENT_KEYS.has(key) && !SERVER_KEYS.has(key)),
208 ) as ClientSettingsPatch;
209 const serverPatch = Object.fromEntries(
210 Object.entries(patch).filter(([key]) => SERVER_KEYS.has(key)),
211 ) as ServerSettingsPatch;
212 const serverKeys = Object.keys(serverPatch);
213 const { connectedEnvironments } = selectScopedSettingsEnvironments(scope, environments, null);
214 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
215 const unscopableKeys = isProjectScope
216 ? serverKeys.filter((key) => !isProjectScopedSettingKey(key))
217 : [];
218 const serverWrites: ScopedServerWrite[] =
219 serverKeys.length === 0
220 ? []
221 : isProjectScope
222 ? unscopableKeys.length > 0
223 ? []
224 : projectOverrideWrites(scope, environments, (current, settings, projectId) => {
225 // Object-valued keys arrive as partial patches (the writing style
226 // rows send one field); an override entry stores the whole value,
227 // so complete the patch from the target's effective value.
228 const effective = resolveProjectSettings(settings, projectId).settings;
229 const next: Record<string, unknown> = { ...current };
230 for (const [key, value] of Object.entries(serverPatch)) {
231 if (key === "worktreeCleanup" && serverPatch.worktreeCleanup?.mode === "custom") {
232 next[key] = {
233 mode: "custom",
234 rules: {
235 ...resolveWorktreeCleanup(settings, projectId),
236 ...serverPatch.worktreeCleanup.rules,
237 },
238 };
239 continue;
240 }
241 // A picker's "Inherit" sends null; for keys whose override
242 // cannot store null that means remove the override.
243 if (
244 value === null &&
245 !isNullableProjectSettingsOverride(key as ProjectScopedServerSettingKey)
246 ) {
247 delete next[key];
248 continue;
249 }
250 const base = effective[key as keyof ServerSettings];
251 next[key] =
252 isPlainObject(value) && isPlainObject(base) ? { ...base, ...value } : value;
253 }
254 return next as ProjectSettingsOverrides;
255 })
256 : scope.kind === "all" || scope.kind === "environment"
257 ? connectedEnvironments.flatMap((environment) => {
258 const previous = environment.serverConfig?.settings;
259 if (!previous) return [];
260 return [
261 {
262 environmentId: environment.environmentId,
263 label: environment.label,
264 previous,
265 patch:
266 previous.worktreeCleanup != null &&
267 serverPatch.storageCleanup &&
268 Object.keys(serverPatch.storageCleanup).some((key) =>
269 key.startsWith("worktree"),
270 )
271 ? {
272 ...serverPatch,
273 worktreeCleanup: {
274 mode: "custom",
275 rules: {
276 ...resolveWorktreeCleanup(previous, null),
277 ...Object.fromEntries(
278 Object.entries(serverPatch.storageCleanup).filter(([key]) =>
279 key.startsWith("worktree"),
280 ),
281 ),
282 },
283 },
284 }
285 : serverPatch,
286 },
287 ];
288 })
289 : [];
290 const hasClientWrite = Object.keys(clientPatch).length > 0;
291 const hasWrite = hasClientWrite || serverWrites.length > 0;
292 const unavailableReason =
293 hasWrite || Object.keys(patch).length === 0
294 ? null
295 : scope.kind === "unavailable"
296 ? scope.message
297 : unscopableKeys.length > 0
298 ? "This setting is environment-wide and cannot be overridden by a project."
299 : isProjectScope
300 ? "Connect the selected checkouts, or update their environments, to save a project override."
301 : `Connect ${scope.kind === "environment" ? scope.label : "an environment"} to save this setting.`;
302 return { clientPatch, hasClientWrite, serverWrites, unavailableReason };
304​
305export function planScopedSettingsClear(
306 scope: ResolvedSettingsScope,
307 environments: readonly ScopedSettingsEnvironment[],
308 keys: readonly ProjectScopedServerSettingKey[],
309) {
310 const serverWrites =
311 scope.kind === "project" || scope.kind === "checkout"
312 ? projectOverrideWrites(scope, environments, (_current, settings, projectId) =>
313 clearProjectSettingsOverrides(settings, projectId, keys),
314 )
315 : [];
316 return {
317 clientPatch: {} as ClientSettingsPatch,
318 hasClientWrite: false,
319 serverWrites,
320 unavailableReason:
321 serverWrites.length > 0
322 ? null
323 : "Connect the selected checkouts, or update their environments, to reset this override.",
324 };
326​
327export interface ProjectOverrideEntry {
328 readonly environmentId: EnvironmentId;
329 readonly projectId: ProjectId;
331​
332export function listProjectOverrides(
333 environments: readonly ScopedSettingsEnvironment[],
334 keys: readonly (keyof ServerSettings)[],
335): readonly ProjectOverrideEntry[] {
336 const scoped = keys.filter(isProjectScopedSettingKey);
337 if (scoped.length === 0) return [];
338 return environments.flatMap((environment) => {
339 const overrides = environment.serverConfig?.settings.projectSettingsOverrides;
340 if (!overrides) return [];
341 return Object.entries(overrides).flatMap(([projectId, entry]) =>
342 scoped.some((key) => Object.hasOwn(entry, key))
343 ? [{ environmentId: environment.environmentId, projectId: projectId as ProjectId }]
344 : [],
345 );
346 });
348​
349export function planProjectOverridesClear(
350 environments: readonly ScopedSettingsEnvironment[],
351 entries: readonly ProjectOverrideEntry[],
352 keys: readonly ProjectScopedServerSettingKey[],
353) {
354 const byId = new Map(environments.map((environment) => [environment.environmentId, environment]));
355 const writes = new Map<EnvironmentId, ScopedServerWrite>();
356 for (const { environmentId, projectId } of entries) {
357 const environment = byId.get(environmentId);
358 if (!environment?.serverConfig || environment.connection.phase !== "connected") continue;
359 const settings = environment.serverConfig.settings;
360 const existing = writes.get(environmentId);
361 writes.set(environmentId, {
362 environmentId,
363 label: environment.label,
364 previous: settings,
365 patch: {
366 projectSettingsOverrides: {
367 ...existing?.patch.projectSettingsOverrides,
368 [projectId]: clearProjectSettingsOverrides(settings, projectId, keys),
369 },
370 },
371 });
372 }
373 const serverWrites = [...writes.values()];
374 return {
375 clientPatch: {} as ClientSettingsPatch,
376 hasClientWrite: false,
377 serverWrites,
378 unavailableReason:
379 serverWrites.length > 0 ? null : "Connect the environments to reset these overrides.",
380 };
382​
383function writeWasDropped(value: unknown, before: unknown, saved: unknown): boolean {
384 if (value === null) return before != null && Equal.equals(saved, before);
385 if (isPlainObject(value) && !Array.isArray(before) && !Array.isArray(saved)) {
386 const field = (source: unknown, key: string) =>
387 isPlainObject(source) ? source[key] : undefined;
388 return Object.entries(value).some(([key, next]) =>
389 writeWasDropped(next, field(before, key), field(saved, key)),
390 );
391 }
392 const unchanged =
393 typeof value === "string" && typeof before === "string"
394 ? value.trim() === before
395 : Equal.equals(value, before);
396 return !unchanged && Equal.equals(saved, before);
398​
399/**
400 * An older server drops keys it does not know, top-level or nested, and still
401 * succeeds. Left unreported, the row stays mixed forever.
402 */
403function droppedSettingKeys(write: ScopedServerWrite, saved: ServerSettings | undefined) {
404 if (saved === undefined) return [];
405 return Object.entries(write.patch).flatMap(([key, value]) =>
406 writeWasDropped(
407 value,
408 write.previous[key as keyof ServerSettings],
409 saved[key as keyof ServerSettings],
410 )
411 ? [key]
412 : [],
413 );
415​
416export async function persistScopedSettingsPatch(
417 plan: ReturnType<typeof planScopedSettingsPatch>,
418 persistServer: (input: {
419 environmentId: EnvironmentId;
420 input: { patch: ServerSettingsPatch };
421 }) => Promise<{
422 readonly _tag: "Success" | "Failure";
423 readonly cause?: Cause.Cause<unknown>;
424 readonly value?: ServerSettings;
425 }>,
426 persistClient: (patch: ClientSettingsPatch) => void,
427) {
428 if (plan.hasClientWrite) persistClient(plan.clientPatch);
429 const results = await Promise.allSettled(
430 plan.serverWrites.map(({ environmentId, patch }) =>
431 persistServer({ environmentId, input: { patch } }),
432 ),
433 );
434 const saved = (index: number) => {
435 const result = results[index];
436 return (
437 result?.status === "fulfilled" &&
438 result.value._tag === "Success" &&
439 droppedSettingKeys(plan.serverWrites[index]!, result.value.value).length === 0
440 );
441 };
442 const failedEnvironments = plan.serverWrites.flatMap((environment, index) => {
443 if (saved(index)) return [];
444 const result = results[index];
445 if (result?.status === "fulfilled" && result.value._tag === "Success") {
446 return [
447 {
448 ...environment,
449 message: "This environment does not support this setting. Update T3 Code on it.",
450 },
451 ];
452 }
453 const error: unknown =
454 result?.status === "rejected"
455 ? result.reason
456 : result?.status === "fulfilled" && result.value.cause
457 ? Cause.squash(result.value.cause)
458 : undefined;
459 return [
460 {
461 ...environment,
462 message:
463 error instanceof Error
464 ? error.message
465 : "The save failed. Try reconnecting and saving again.",
466 },
467 ];
468 });
469 const savedEnvironments = plan.serverWrites.filter((_, index) => saved(index));
470 return {
471 failedEnvironments,
472 savedEnvironments,
473 savedEnvironmentCount: savedEnvironments.length,
474 };