Route web persistence through the local API bridge
- Remove the clientPersistence wrapper layer - Read and write settings and saved environments via ensureLocalApi() - Refresh persistence tests to cover the new storage and hydration paths
This commit is contained in:
1 parent
1363cc1189
commit
e56b58c60e
6 files changed
+118
-322
No files matched your search
@@ -1,179 +0,0 @@
|
||||
import { EnvironmentId, type ClientSettings, type LocalApi } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
CLIENT_SETTINGS_STORAGE_KEY,
|
||||
readPersistedClientSettings,
|
||||
readPersistedSavedEnvironmentSecret,
|
||||
writePersistedClientSettings,
|
||||
writePersistedSavedEnvironmentRegistry,
|
||||
writePersistedSavedEnvironmentSecret,
|
||||
} from "./clientPersistence";
|
||||
import {
|
||||
readBrowserClientSettings,
|
||||
readBrowserSavedEnvironmentRegistry,
|
||||
readBrowserSavedEnvironmentSecret,
|
||||
removeBrowserSavedEnvironmentSecret,
|
||||
writeBrowserClientSettings,
|
||||
writeBrowserSavedEnvironmentRegistry,
|
||||
writeBrowserSavedEnvironmentSecret,
|
||||
} from "./clientPersistenceStorage";
|
||||
|
||||
const testEnvironmentId = EnvironmentId.makeUnsafe("environment-1");
|
||||
|
||||
const clientSettings: ClientSettings = {
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffWordWrap: true,
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
timestampFormat: "24-hour",
|
||||
};
|
||||
|
||||
function createLocalStorageStub(): Storage {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
removeItem: (key) => {
|
||||
store.delete(key);
|
||||
},
|
||||
clear: () => {
|
||||
store.clear();
|
||||
},
|
||||
key: (index) => [...store.keys()][index] ?? null,
|
||||
get length() {
|
||||
return store.size;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function getTestWindow(): Window & typeof globalThis {
|
||||
const localStorage = createLocalStorageStub();
|
||||
const testWindow = {
|
||||
localStorage,
|
||||
location: {
|
||||
origin: "http://localhost:3000",
|
||||
},
|
||||
} as Window & typeof globalThis;
|
||||
vi.stubGlobal("window", testWindow);
|
||||
vi.stubGlobal("localStorage", localStorage);
|
||||
return testWindow;
|
||||
}
|
||||
|
||||
function installBrowserPersistenceApi(windowForTest: Window & typeof globalThis): void {
|
||||
windowForTest.nativeApi = {
|
||||
persistence: {
|
||||
getClientSettings: async () => readBrowserClientSettings(),
|
||||
setClientSettings: async (settings: ClientSettings) => {
|
||||
writeBrowserClientSettings(settings);
|
||||
},
|
||||
getSavedEnvironmentRegistry: async () => readBrowserSavedEnvironmentRegistry(),
|
||||
setSavedEnvironmentRegistry: async (
|
||||
records: Awaited<ReturnType<LocalApi["persistence"]["getSavedEnvironmentRegistry"]>>,
|
||||
) => {
|
||||
writeBrowserSavedEnvironmentRegistry(records);
|
||||
},
|
||||
getSavedEnvironmentSecret: async (
|
||||
environmentId: Parameters<LocalApi["persistence"]["getSavedEnvironmentSecret"]>[0],
|
||||
) => readBrowserSavedEnvironmentSecret(environmentId),
|
||||
setSavedEnvironmentSecret: async (
|
||||
environmentId: Parameters<LocalApi["persistence"]["setSavedEnvironmentSecret"]>[0],
|
||||
secret: Parameters<LocalApi["persistence"]["setSavedEnvironmentSecret"]>[1],
|
||||
) => writeBrowserSavedEnvironmentSecret(environmentId, secret),
|
||||
removeSavedEnvironmentSecret: async (
|
||||
environmentId: Parameters<LocalApi["persistence"]["removeSavedEnvironmentSecret"]>[0],
|
||||
) => {
|
||||
removeBrowserSavedEnvironmentSecret(environmentId);
|
||||
},
|
||||
},
|
||||
} as unknown as LocalApi;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
const { __resetLocalApiForTests } = await import("./localApi");
|
||||
await __resetLocalApiForTests();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function resetLocalApiForTest(): Promise<void> {
|
||||
const { __resetLocalApiForTests } = await import("./localApi");
|
||||
await __resetLocalApiForTests();
|
||||
}
|
||||
|
||||
describe("clientPersistence", () => {
|
||||
it("reads and writes client settings in browser storage mode", async () => {
|
||||
const testWindow = getTestWindow();
|
||||
installBrowserPersistenceApi(testWindow);
|
||||
await resetLocalApiForTest();
|
||||
|
||||
await writePersistedClientSettings(clientSettings);
|
||||
|
||||
await expect(readPersistedClientSettings()).resolves.toEqual(clientSettings);
|
||||
});
|
||||
|
||||
it("reads saved environment bearer tokens from browser storage mode", async () => {
|
||||
const testWindow = getTestWindow();
|
||||
installBrowserPersistenceApi(testWindow);
|
||||
await resetLocalApiForTest();
|
||||
writeBrowserSavedEnvironmentRegistry([
|
||||
{
|
||||
environmentId: testEnvironmentId,
|
||||
label: "Remote environment",
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
createdAt: "2026-04-09T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
},
|
||||
]);
|
||||
writeBrowserSavedEnvironmentSecret(testEnvironmentId, "bearer-token");
|
||||
|
||||
await expect(readPersistedSavedEnvironmentSecret(testEnvironmentId)).resolves.toBe(
|
||||
"bearer-token",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves browser-mode secrets when the secret is written before metadata", async () => {
|
||||
const testWindow = getTestWindow();
|
||||
installBrowserPersistenceApi(testWindow);
|
||||
await resetLocalApiForTest();
|
||||
|
||||
await writePersistedSavedEnvironmentSecret(testEnvironmentId, "bearer-token");
|
||||
await writePersistedSavedEnvironmentRegistry([
|
||||
{
|
||||
environmentId: testEnvironmentId,
|
||||
label: "Remote environment",
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
createdAt: "2026-04-09T00:00:00.000Z",
|
||||
lastConnectedAt: null,
|
||||
},
|
||||
]);
|
||||
|
||||
await expect(readPersistedSavedEnvironmentSecret(testEnvironmentId)).resolves.toBe(
|
||||
"bearer-token",
|
||||
);
|
||||
});
|
||||
|
||||
it("can read client settings through the desktop bridge", async () => {
|
||||
const testWindow = getTestWindow();
|
||||
testWindow.nativeApi = {
|
||||
persistence: {
|
||||
getClientSettings: async () => clientSettings,
|
||||
setClientSettings: async () => undefined,
|
||||
getSavedEnvironmentRegistry: async () => [],
|
||||
setSavedEnvironmentRegistry: async () => undefined,
|
||||
getSavedEnvironmentSecret: async () => null,
|
||||
setSavedEnvironmentSecret: async () => true,
|
||||
removeSavedEnvironmentSecret: async () => undefined,
|
||||
},
|
||||
} as unknown as LocalApi;
|
||||
await resetLocalApiForTest();
|
||||
|
||||
await expect(readPersistedClientSettings()).resolves.toEqual(clientSettings);
|
||||
expect(testWindow.localStorage.getItem(CLIENT_SETTINGS_STORAGE_KEY)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,49 +0,0 @@
|
||||
import {
|
||||
type ClientSettings,
|
||||
type EnvironmentId,
|
||||
type PersistedSavedEnvironmentRecord,
|
||||
} from "@t3tools/contracts";
|
||||
import { ensureLocalApi } from "./localApi";
|
||||
export {
|
||||
CLIENT_SETTINGS_STORAGE_KEY,
|
||||
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
|
||||
} from "./clientPersistenceStorage";
|
||||
|
||||
export async function readPersistedClientSettings(): Promise<ClientSettings | null> {
|
||||
return ensureLocalApi().persistence.getClientSettings();
|
||||
}
|
||||
|
||||
export async function writePersistedClientSettings(settings: ClientSettings): Promise<void> {
|
||||
await ensureLocalApi().persistence.setClientSettings(settings);
|
||||
}
|
||||
|
||||
export async function readPersistedSavedEnvironmentRegistry(): Promise<
|
||||
ReadonlyArray<PersistedSavedEnvironmentRecord>
|
||||
> {
|
||||
return ensureLocalApi().persistence.getSavedEnvironmentRegistry();
|
||||
}
|
||||
|
||||
export async function writePersistedSavedEnvironmentRegistry(
|
||||
records: ReadonlyArray<PersistedSavedEnvironmentRecord>,
|
||||
): Promise<void> {
|
||||
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(records);
|
||||
}
|
||||
|
||||
export async function readPersistedSavedEnvironmentSecret(
|
||||
environmentId: EnvironmentId,
|
||||
): Promise<string | null> {
|
||||
return ensureLocalApi().persistence.getSavedEnvironmentSecret(environmentId);
|
||||
}
|
||||
|
||||
export async function writePersistedSavedEnvironmentSecret(
|
||||
environmentId: EnvironmentId,
|
||||
secret: string,
|
||||
): Promise<boolean> {
|
||||
return ensureLocalApi().persistence.setSavedEnvironmentSecret(environmentId, secret);
|
||||
}
|
||||
|
||||
export async function removePersistedSavedEnvironmentSecret(
|
||||
environmentId: EnvironmentId,
|
||||
): Promise<void> {
|
||||
await ensureLocalApi().persistence.removeSavedEnvironmentSecret(environmentId);
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
import {
|
||||
ClientSettingsSchema,
|
||||
type ClientSettings,
|
||||
type EnvironmentId,
|
||||
EnvironmentId,
|
||||
type EnvironmentId as EnvironmentIdValue,
|
||||
type PersistedSavedEnvironmentRecord,
|
||||
} from "@t3tools/contracts";
|
||||
import { Predicate, Schema } from "effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
|
||||
export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
|
||||
export const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
|
||||
@@ -14,7 +17,7 @@ interface BrowserSavedEnvironmentRecord extends PersistedSavedEnvironmentRecord
|
||||
}
|
||||
|
||||
interface BrowserSavedEnvironmentRegistryState {
|
||||
readonly byId?: Record<string, BrowserSavedEnvironmentRecord>;
|
||||
readonly byId?: Record<string, unknown>;
|
||||
readonly secretsById?: Record<string, string>;
|
||||
}
|
||||
|
||||
@@ -23,53 +26,54 @@ interface BrowserSavedEnvironmentRegistryDocument {
|
||||
readonly version?: number;
|
||||
}
|
||||
|
||||
const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema);
|
||||
const encodeClientSettings = Schema.encodeSync(Schema.fromJsonString(ClientSettingsSchema));
|
||||
const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
|
||||
environmentId: EnvironmentId,
|
||||
label: Schema.String,
|
||||
httpBaseUrl: Schema.String,
|
||||
wsBaseUrl: Schema.String,
|
||||
createdAt: Schema.String,
|
||||
lastConnectedAt: Schema.NullOr(Schema.String),
|
||||
bearerToken: Schema.optionalKey(Schema.String),
|
||||
});
|
||||
|
||||
const BrowserSavedEnvironmentRegistryDocumentSchema = Schema.Struct({
|
||||
version: Schema.optionalKey(Schema.Number),
|
||||
state: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
byId: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
secretsById: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const decodeBrowserSavedEnvironmentRecord = Schema.decodeUnknownSync(
|
||||
BrowserSavedEnvironmentRecordSchema,
|
||||
);
|
||||
|
||||
function hasWindow(): boolean {
|
||||
return typeof window !== "undefined";
|
||||
}
|
||||
|
||||
function readJson(rawValue: string | null): unknown {
|
||||
if (!rawValue) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeBrowserSavedEnvironmentRecord(
|
||||
value: unknown,
|
||||
): BrowserSavedEnvironmentRecord | null {
|
||||
try {
|
||||
return JSON.parse(rawValue);
|
||||
return decodeBrowserSavedEnvironmentRecord(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isPersistedSavedEnvironmentRecord(
|
||||
value: unknown,
|
||||
): value is PersistedSavedEnvironmentRecord & { readonly bearerToken?: unknown } {
|
||||
return (
|
||||
Predicate.isObject(value) &&
|
||||
typeof value.environmentId === "string" &&
|
||||
typeof value.label === "string" &&
|
||||
typeof value.httpBaseUrl === "string" &&
|
||||
typeof value.wsBaseUrl === "string" &&
|
||||
typeof value.createdAt === "string" &&
|
||||
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string")
|
||||
);
|
||||
}
|
||||
|
||||
function normalizePersistedSavedEnvironmentRecord(
|
||||
value: unknown,
|
||||
): PersistedSavedEnvironmentRecord | null {
|
||||
if (!isPersistedSavedEnvironmentRecord(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function toPersistedSavedEnvironmentRecord(
|
||||
record: PersistedSavedEnvironmentRecord,
|
||||
): PersistedSavedEnvironmentRecord {
|
||||
return {
|
||||
environmentId: value.environmentId,
|
||||
label: value.label,
|
||||
httpBaseUrl: value.httpBaseUrl,
|
||||
wsBaseUrl: value.wsBaseUrl,
|
||||
createdAt: value.createdAt,
|
||||
lastConnectedAt: value.lastConnectedAt,
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -79,8 +83,7 @@ export function readBrowserClientSettings(): ClientSettings | null {
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = window.localStorage.getItem(CLIENT_SETTINGS_STORAGE_KEY);
|
||||
return raw ? decodeClientSettings(JSON.parse(raw)) : null;
|
||||
return getLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, ClientSettingsSchema);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -91,7 +94,7 @@ export function writeBrowserClientSettings(settings: ClientSettings): void {
|
||||
return;
|
||||
}
|
||||
|
||||
window.localStorage.setItem(CLIENT_SETTINGS_STORAGE_KEY, encodeClientSettings(settings));
|
||||
setLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, settings, ClientSettingsSchema);
|
||||
}
|
||||
|
||||
function readBrowserSavedEnvironmentRegistryDocument(): BrowserSavedEnvironmentRegistryDocument {
|
||||
@@ -99,9 +102,16 @@ function readBrowserSavedEnvironmentRegistryDocument(): BrowserSavedEnvironmentR
|
||||
return {};
|
||||
}
|
||||
|
||||
const raw = window.localStorage.getItem(SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY);
|
||||
const parsed = readJson(raw);
|
||||
return Predicate.isObject(parsed) ? (parsed as BrowserSavedEnvironmentRegistryDocument) : {};
|
||||
try {
|
||||
return (
|
||||
getLocalStorageItem(
|
||||
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
|
||||
BrowserSavedEnvironmentRegistryDocumentSchema,
|
||||
) ?? {}
|
||||
);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeBrowserSavedEnvironmentRegistryDocument(
|
||||
@@ -111,7 +121,11 @@ function writeBrowserSavedEnvironmentRegistryDocument(
|
||||
return;
|
||||
}
|
||||
|
||||
window.localStorage.setItem(SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY, JSON.stringify(document));
|
||||
setLocalStorageItem(
|
||||
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
|
||||
document,
|
||||
BrowserSavedEnvironmentRegistryDocumentSchema,
|
||||
);
|
||||
}
|
||||
|
||||
function readBrowserSavedEnvironmentRecordsWithSecrets(): ReadonlyArray<BrowserSavedEnvironmentRecord> {
|
||||
@@ -119,7 +133,7 @@ function readBrowserSavedEnvironmentRecordsWithSecrets(): ReadonlyArray<BrowserS
|
||||
const byId = state?.byId ?? {};
|
||||
const secretsById = state?.secretsById ?? {};
|
||||
return Object.values(byId).flatMap((record) => {
|
||||
const normalizedRecord = normalizePersistedSavedEnvironmentRecord(record);
|
||||
const normalizedRecord = normalizeBrowserSavedEnvironmentRecord(record);
|
||||
if (!normalizedRecord) {
|
||||
return [];
|
||||
}
|
||||
@@ -128,8 +142,9 @@ function readBrowserSavedEnvironmentRecordsWithSecrets(): ReadonlyArray<BrowserS
|
||||
typeof secretsById[normalizedRecord.environmentId] === "string" &&
|
||||
secretsById[normalizedRecord.environmentId]
|
||||
? secretsById[normalizedRecord.environmentId]
|
||||
: typeof record.bearerToken === "string" && record.bearerToken.length > 0
|
||||
? record.bearerToken
|
||||
: typeof normalizedRecord.bearerToken === "string" &&
|
||||
normalizedRecord.bearerToken.length > 0
|
||||
? normalizedRecord.bearerToken
|
||||
: null;
|
||||
|
||||
return [
|
||||
@@ -158,14 +173,9 @@ function writeBrowserSavedEnvironmentRecords(
|
||||
}
|
||||
|
||||
export function readBrowserSavedEnvironmentRegistry(): ReadonlyArray<PersistedSavedEnvironmentRecord> {
|
||||
return readBrowserSavedEnvironmentRecordsWithSecrets().map((record) => ({
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
}));
|
||||
return readBrowserSavedEnvironmentRecordsWithSecrets().map((record) =>
|
||||
toPersistedSavedEnvironmentRecord(record),
|
||||
);
|
||||
}
|
||||
|
||||
export function writeBrowserSavedEnvironmentRegistry(
|
||||
@@ -193,7 +203,9 @@ export function writeBrowserSavedEnvironmentRegistry(
|
||||
);
|
||||
}
|
||||
|
||||
export function readBrowserSavedEnvironmentSecret(environmentId: EnvironmentId): string | null {
|
||||
export function readBrowserSavedEnvironmentSecret(
|
||||
environmentId: EnvironmentIdValue,
|
||||
): string | null {
|
||||
const state = readBrowserSavedEnvironmentRegistryDocument().state;
|
||||
const directSecret = state?.secretsById?.[environmentId];
|
||||
if (typeof directSecret === "string" && directSecret.length > 0) {
|
||||
@@ -208,13 +220,13 @@ export function readBrowserSavedEnvironmentSecret(environmentId: EnvironmentId):
|
||||
}
|
||||
|
||||
export function writeBrowserSavedEnvironmentSecret(
|
||||
environmentId: EnvironmentId,
|
||||
environmentId: EnvironmentIdValue,
|
||||
secret: string,
|
||||
): boolean {
|
||||
const document = readBrowserSavedEnvironmentRegistryDocument();
|
||||
const state = document.state ?? {};
|
||||
const byId = state.byId ?? {};
|
||||
const existingRecord = byId[environmentId];
|
||||
const existingRecord = normalizeBrowserSavedEnvironmentRecord(byId[environmentId]);
|
||||
writeBrowserSavedEnvironmentRegistryDocument({
|
||||
version: document.version ?? 1,
|
||||
state: {
|
||||
@@ -236,22 +248,15 @@ export function writeBrowserSavedEnvironmentSecret(
|
||||
return true;
|
||||
}
|
||||
|
||||
export function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentId): void {
|
||||
export function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentIdValue): void {
|
||||
const document = readBrowserSavedEnvironmentRegistryDocument();
|
||||
const state = document.state ?? {};
|
||||
const byId = { ...state.byId };
|
||||
const existingRecord = byId[environmentId];
|
||||
const existingRecord = normalizeBrowserSavedEnvironmentRecord(byId[environmentId]);
|
||||
const nextById = existingRecord
|
||||
? {
|
||||
...byId,
|
||||
[environmentId]: {
|
||||
environmentId: existingRecord.environmentId,
|
||||
label: existingRecord.label,
|
||||
httpBaseUrl: existingRecord.httpBaseUrl,
|
||||
wsBaseUrl: existingRecord.wsBaseUrl,
|
||||
createdAt: existingRecord.createdAt,
|
||||
lastConnectedAt: existingRecord.lastConnectedAt,
|
||||
},
|
||||
[environmentId]: toPersistedSavedEnvironmentRecord(existingRecord),
|
||||
}
|
||||
: byId;
|
||||
const { [environmentId]: _removed, ...remainingSecrets } = state.secretsById ?? {};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EnvironmentId, type LocalApi } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
resetSavedEnvironmentRegistryStoreForTests,
|
||||
@@ -9,9 +9,30 @@ import {
|
||||
} from "./catalog";
|
||||
|
||||
describe("environment runtime catalog stores", () => {
|
||||
afterEach(() => {
|
||||
beforeEach(async () => {
|
||||
vi.stubGlobal("window", {
|
||||
nativeApi: {
|
||||
persistence: {
|
||||
getClientSettings: async () => null,
|
||||
setClientSettings: async () => undefined,
|
||||
getSavedEnvironmentRegistry: async () => [],
|
||||
setSavedEnvironmentRegistry: async () => undefined,
|
||||
getSavedEnvironmentSecret: async () => null,
|
||||
setSavedEnvironmentSecret: async () => true,
|
||||
removeSavedEnvironmentSecret: async () => undefined,
|
||||
},
|
||||
} satisfies Pick<LocalApi, "persistence">,
|
||||
});
|
||||
const { __resetLocalApiForTests } = await import("../../localApi");
|
||||
await __resetLocalApiForTests();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
resetSavedEnvironmentRegistryStoreForTests();
|
||||
resetSavedEnvironmentRuntimeStoreForTests();
|
||||
const { __resetLocalApiForTests } = await import("../../localApi");
|
||||
await __resetLocalApiForTests();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("resets the saved environment registry store state", () => {
|
||||
|
||||
@@ -8,13 +8,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
|
||||
import {
|
||||
readPersistedSavedEnvironmentRegistry,
|
||||
readPersistedSavedEnvironmentSecret,
|
||||
removePersistedSavedEnvironmentSecret,
|
||||
writePersistedSavedEnvironmentRegistry,
|
||||
writePersistedSavedEnvironmentSecret,
|
||||
} from "../../clientPersistence";
|
||||
import { ensureLocalApi } from "../../localApi";
|
||||
import { getPrimaryKnownEnvironment } from "../primary";
|
||||
|
||||
export interface SavedEnvironmentRecord {
|
||||
@@ -56,11 +50,13 @@ function toPersistedSavedEnvironmentRecord(
|
||||
function persistSavedEnvironmentRegistryState(
|
||||
byId: Record<EnvironmentId, SavedEnvironmentRecord>,
|
||||
): void {
|
||||
void writePersistedSavedEnvironmentRegistry(
|
||||
Object.values(byId).map((record) => toPersistedSavedEnvironmentRecord(record)),
|
||||
).catch((error) => {
|
||||
console.error("[SAVED_ENVIRONMENTS] persist failed", error);
|
||||
});
|
||||
void ensureLocalApi()
|
||||
.persistence.setSavedEnvironmentRegistry(
|
||||
Object.values(byId).map((record) => toPersistedSavedEnvironmentRecord(record)),
|
||||
)
|
||||
.catch((error) => {
|
||||
console.error("[SAVED_ENVIRONMENTS] persist failed", error);
|
||||
});
|
||||
}
|
||||
|
||||
function replaceSavedEnvironmentRegistryState(
|
||||
@@ -81,7 +77,7 @@ async function hydrateSavedEnvironmentRegistry(): Promise<void> {
|
||||
|
||||
const nextHydration = (async () => {
|
||||
try {
|
||||
const persistedRecords = await readPersistedSavedEnvironmentRegistry();
|
||||
const persistedRecords = await ensureLocalApi().persistence.getSavedEnvironmentRegistry();
|
||||
replaceSavedEnvironmentRegistryState(persistedRecords);
|
||||
} catch (error) {
|
||||
console.error("[SAVED_ENVIRONMENTS] hydrate failed", error);
|
||||
@@ -203,20 +199,20 @@ export function resetSavedEnvironmentRegistryStoreForTests() {
|
||||
export async function readSavedEnvironmentBearerToken(
|
||||
environmentId: EnvironmentId,
|
||||
): Promise<string | null> {
|
||||
return readPersistedSavedEnvironmentSecret(environmentId);
|
||||
return ensureLocalApi().persistence.getSavedEnvironmentSecret(environmentId);
|
||||
}
|
||||
|
||||
export async function writeSavedEnvironmentBearerToken(
|
||||
environmentId: EnvironmentId,
|
||||
bearerToken: string,
|
||||
): Promise<boolean> {
|
||||
return writePersistedSavedEnvironmentSecret(environmentId, bearerToken);
|
||||
return ensureLocalApi().persistence.setSavedEnvironmentSecret(environmentId, bearerToken);
|
||||
}
|
||||
|
||||
export async function removeSavedEnvironmentBearerToken(
|
||||
environmentId: EnvironmentId,
|
||||
): Promise<void> {
|
||||
await removePersistedSavedEnvironmentSecret(environmentId);
|
||||
await ensureLocalApi().persistence.removeSavedEnvironmentSecret(environmentId);
|
||||
}
|
||||
|
||||
export type SavedEnvironmentConnectionState = "connecting" | "connected" | "disconnected" | "error";
|
||||
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
TimestampFormat,
|
||||
UnifiedSettings,
|
||||
} from "@t3tools/contracts/settings";
|
||||
import { readPersistedClientSettings, writePersistedClientSettings } from "~/clientPersistence";
|
||||
import { ensureLocalApi } from "~/localApi";
|
||||
import { normalizeCustomModelSlugs } from "~/modelSelection";
|
||||
import { Predicate, Schema, Struct } from "effect";
|
||||
@@ -74,7 +73,7 @@ async function hydrateClientSettings(): Promise<void> {
|
||||
|
||||
const nextHydration = (async () => {
|
||||
try {
|
||||
const persistedSettings = await readPersistedClientSettings();
|
||||
const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
|
||||
if (persistedSettings) {
|
||||
replaceClientSettingsSnapshot(persistedSettings);
|
||||
}
|
||||
@@ -97,9 +96,11 @@ async function hydrateClientSettings(): Promise<void> {
|
||||
|
||||
function persistClientSettings(settings: ClientSettings): void {
|
||||
replaceClientSettingsSnapshot(settings);
|
||||
void writePersistedClientSettings(settings).catch((error) => {
|
||||
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, error);
|
||||
});
|
||||
void ensureLocalApi()
|
||||
.persistence.setClientSettings(settings)
|
||||
.catch((error) => {
|
||||
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, error);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Key sets for routing patches ─────────────────────────────────────
|
||||
@@ -304,7 +305,8 @@ export function migrateLocalSettingsToServer(): void {
|
||||
const clientPatch = buildLegacyClientSettingsMigrationPatch(old);
|
||||
if (Object.keys(clientPatch).length > 0) {
|
||||
void (async () => {
|
||||
const current = (await readPersistedClientSettings()) ?? DEFAULT_CLIENT_SETTINGS;
|
||||
const current =
|
||||
(await ensureLocalApi().persistence.getClientSettings()) ?? DEFAULT_CLIENT_SETTINGS;
|
||||
persistClientSettings({
|
||||
...current,
|
||||
...clientPatch,
|
||||
|
||||
Reference in new issue
Block a user