Open History to see the last commit
1import * as Arr from "effect/Array";
2import { pipe } from "effect/Function";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import * as SecureStore from "expo-secure-store";
6import { EnvironmentId, OrchestrationShellSnapshot } from "@t3tools/contracts";
7
8import type { SavedRemoteConnection } from "./connection";
9
10const CONNECTIONS_KEY = "t3code.connections";
11const PREFERENCES_KEY = "t3code.preferences";
12const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
13const SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
14
15export interface CachedShellSnapshot {
16 readonly schemaVersion: typeof SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION;
17 readonly environmentId: EnvironmentId;
18 readonly snapshotReceivedAt: string;
19 readonly snapshot: OrchestrationShellSnapshot;
20}
21
22export interface MobilePreferences {
23 readonly terminalFontSize?: number;
24}
25
26const CachedShellSnapshotSchema = Schema.Struct({
27 schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
28 environmentId: EnvironmentId,
29 snapshotReceivedAt: Schema.String,
30 snapshot: OrchestrationShellSnapshot,
31});
32const decodeCachedShellSnapshot = Schema.decodeUnknownOption(CachedShellSnapshotSchema);
33
34async function readStorageItem(key: string): Promise<string | null> {
35 return await SecureStore.getItemAsync(key);
36}
37
38async function writeStorageItem(key: string, value: string): Promise<void> {
39 await SecureStore.setItemAsync(key, value);
40}
41
42async function readJsonStorageItem<T>(key: string): Promise<T | null> {
43 const raw = (await readStorageItem(key)) ?? "";
44 if (!raw.trim()) {
45 return null;
46 }
47
48 try {
49 return JSON.parse(raw) as T;
50 } catch {
51 return null;
52 }
53}
54
55function cachedShellSnapshotFileName(environmentId: EnvironmentId): string {
56 return `${encodeURIComponent(environmentId)}.json`;
57}
58
59async function getShellSnapshotCacheDirectory() {
60 const { Directory, Paths } = await import("expo-file-system");
61 const directory = new Directory(Paths.document, SHELL_SNAPSHOT_CACHE_DIRECTORY);
62 directory.create({ idempotent: true, intermediates: true });
63 return directory;
64}
65
66export async function loadCachedShellSnapshot(
67 environmentId: EnvironmentId,
68): Promise<CachedShellSnapshot | null> {
69 try {
70 const { File } = await import("expo-file-system");
71 const directory = await getShellSnapshotCacheDirectory();
72 const file = new File(directory, cachedShellSnapshotFileName(environmentId));
73 if (!file.exists) {
74 return null;
75 }
76
77 const parsed = JSON.parse(await file.text()) as unknown;
78 const decoded = decodeCachedShellSnapshot(parsed);
79 if (Option.isNone(decoded) || decoded.value.environmentId !== environmentId) {
80 return null;
81 }
82
83 return decoded.value;
84 } catch {
85 return null;
86 }
87}
88
89export async function saveCachedShellSnapshot(
90 environmentId: EnvironmentId,
91 snapshot: OrchestrationShellSnapshot,
92): Promise<void> {
93 try {
94 const { File } = await import("expo-file-system");
95 const directory = await getShellSnapshotCacheDirectory();
96 const file = new File(directory, cachedShellSnapshotFileName(environmentId));
97 const document: CachedShellSnapshot = {
98 schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
99 environmentId,
100 snapshotReceivedAt: new Date().toISOString(),
101 snapshot,
102 };
103
104 if (!file.exists) {
105 file.create({ intermediates: true, overwrite: true });
106 }
107 file.write(JSON.stringify(document));
108 } catch {
109 // Cache persistence is best-effort and should never block live data.
110 }
111}
112
113export async function clearCachedShellSnapshot(environmentId: EnvironmentId): Promise<void> {
114 try {
115 const { File } = await import("expo-file-system");
116 const directory = await getShellSnapshotCacheDirectory();
117 const file = new File(directory, cachedShellSnapshotFileName(environmentId));
118 if (file.exists) {
119 file.delete();
120 }
121 } catch {
122 // Ignore cache cleanup failures.
123 }
124}
125
126export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
127 const parsed = await readJsonStorageItem<{
128 readonly connections?: ReadonlyArray<SavedRemoteConnection>;
129 }>(CONNECTIONS_KEY);
130 if (!parsed) {
131 return [];
132 }
133
134 return pipe(
135 parsed.connections ?? [],
136 Arr.filter((c) => !!c.environmentId && !!c.bearerToken?.trim()),
137 );
138}
139
140export async function saveConnection(connection: SavedRemoteConnection): Promise<void> {
141 const current = await loadSavedConnections();
142 const next = current.some((entry) => entry.environmentId === connection.environmentId)
143 ? pipe(
144 current,
145 Arr.map((entry) => (entry.environmentId === connection.environmentId ? connection : entry)),
146 )
147 : pipe(current, Arr.append(connection));
148
149 await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
150}
151
152export async function clearSavedConnection(environmentId: EnvironmentId): Promise<void> {
153 const current = await loadSavedConnections();
154 const next = pipe(
155 current,
156 Arr.filter((entry) => entry.environmentId !== environmentId),
157 );
158 await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
159}
160
161export async function loadPreferences(): Promise<MobilePreferences> {
162 const parsed = await readJsonStorageItem<MobilePreferences>(PREFERENCES_KEY);
163 if (!parsed || typeof parsed !== "object") {
164 return {};
165 }
166
167 if (typeof parsed.terminalFontSize === "number") {
168 return { terminalFontSize: parsed.terminalFontSize };
169 }
170
171 return {};
172}
173
174export async function savePreferencesPatch(
175 patch: Partial<MobilePreferences>,
176): Promise<MobilePreferences> {
177 const current = await loadPreferences();
178 const next: MobilePreferences = {
179 ...current,
180 ...patch,
181 };
182 await writeStorageItem(PREFERENCES_KEY, JSON.stringify(next));
183 return next;
184}