Something went wrong. Try again.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256import { type Collection, createCollection, localOnlyCollectionOptions } from "@tanstack/db";import { rxdbCollectionOptions } from "@tanstack/rxdb-db-collection";import type { GitHost, RepoRef } from "@/lib/git-host/types";
export type StorageTier = "state" | "permanent";
const DATA_DATABASE_NAME = "pullrequestdotreview_data_v1";const STATE_TTL_MS = 30 * 24 * 60 * 60 * 1000;const LEGACY_RESET_METADATA_ID = "legacy_reset_v1";
const APP_PREFERENCES_COLLECTION_NAME = "app_preferences";const REVIEW_VIEWED_STATE_COLLECTION_NAME = "review_viewed_state";const REVIEW_DIRECTORY_STATE_COLLECTION_NAME = "review_directory_state";const REVIEW_LAYOUT_STATE_COLLECTION_NAME = "review_layout_state";const INLINE_COMMENT_DRAFTS_COLLECTION_NAME = "inline_comment_drafts";const INLINE_COMMENT_ACTIVE_DRAFT_COLLECTION_NAME = "inline_comment_active_draft";const APP_METADATA_COLLECTION_NAME = "app_metadata";
const APP_PREFERENCES_COLLECTION_ID = "app-preferences:rxdb";const REVIEW_VIEWED_STATE_COLLECTION_ID = "review-viewed-state:rxdb";const REVIEW_DIRECTORY_STATE_COLLECTION_ID = "review-directory-state:rxdb";const REVIEW_LAYOUT_STATE_COLLECTION_ID = "review-layout-state:rxdb";const INLINE_COMMENT_DRAFTS_COLLECTION_ID = "inline-comment-drafts:rxdb";const INLINE_COMMENT_ACTIVE_DRAFT_COLLECTION_ID = "inline-comment-active-draft:rxdb";const APP_METADATA_COLLECTION_ID = "app-metadata:rxdb";
const APPEARANCE_RECORD_ID = "appearance";const DIFF_OPTIONS_RECORD_ID = "diff-options";const TREE_SETTINGS_RECORD_ID = "tree-settings";const SHORTCUTS_RECORD_ID = "shortcuts";const HOST_PREFERENCES_RECORD_ID = "host-preferences";const REVIEW_LAYOUT_RECORD_ID = "review-layout";
const LOCAL_STORAGE_RESET_PREFIX = "pr_review_";
type BaseCollectionRecord = { id: string; updatedAt: number; expiresAt: number | null;};
type AppPreferenceRecord = BaseCollectionRecord & { value: Record<string, unknown>;};
type AppearanceSettingsRecord = BaseCollectionRecord & { id: typeof APPEARANCE_RECORD_ID; appThemeMode: "auto" | "light" | "dark"; sansFontFamily: string; monospaceFontFamily: string; sansFontSize: number; sansLineHeight: number; monospaceFontSize: number; monospaceLineHeight: number; treeUseCustomTypography: boolean; treeFontFamily: string; treeFontSize: number; treeLineHeight: number;};
type DiffOptionsRecord = BaseCollectionRecord & { id: typeof DIFF_OPTIONS_RECORD_ID; followSystemTheme: boolean; theme: string; diffUseCustomTypography: boolean; diffFontFamily: string; diffFontSize: number; diffLineHeight: number; diffStyle: "unified" | "split"; diffIndicators: "classic" | "bars" | "none"; disableBackground: boolean; hunkSeparators: "simple" | "metadata" | "line-info"; expandUnchanged: boolean; expansionLineCount: number; collapsedContextThreshold: number; lineDiffType: "word-alt" | "word" | "char" | "none"; disableLineNumbers: boolean; overflow: "scroll" | "wrap"; collapseViewedFilesByDefault: boolean; autoMarkViewedFiles: boolean;};
type TreeSettingsRecord = BaseCollectionRecord & { id: typeof TREE_SETTINGS_RECORD_ID; compactSingleChildDirectories: boolean; treeIndentSize: number;};
type ShortcutConfigRecord = { key: string; modifiers: { ctrl?: boolean; alt?: boolean; shift?: boolean; meta?: boolean; }; description: string;};
type ShortcutsRecord = BaseCollectionRecord & { id: typeof SHORTCUTS_RECORD_ID; nextUnviewedFile: ShortcutConfigRecord; previousUnviewedFile: ShortcutConfigRecord; scrollDown: ShortcutConfigRecord; scrollUp: ShortcutConfigRecord; nextFile: ShortcutConfigRecord; previousFile: ShortcutConfigRecord; markFileViewed: ShortcutConfigRecord; markFileViewedAndFold: ShortcutConfigRecord; approvePullRequest: ShortcutConfigRecord; requestChangesPullRequest: ShortcutConfigRecord;};
type HostPreferencesRecord = BaseCollectionRecord & { id: typeof HOST_PREFERENCES_RECORD_ID; activeHost: GitHost; reposByHost: Record<GitHost, RepoRef[]>;};
type BitbucketAuthCredentialRecord = BaseCollectionRecord & { id: "bitbucket"; host: "bitbucket"; email: string; apiToken: string;};
type GithubAuthCredentialRecord = BaseCollectionRecord & { id: "github"; host: "github"; token: string;};
type ReviewViewedStateRecord = BaseCollectionRecord & { id: string; viewedVersionIds: string[];};
type ReviewDirectoryStateRecord = BaseCollectionRecord & { id: string; expandedByPath: Record<string, boolean>;};
type ReviewViewMode = "single" | "all";
type ReviewLayoutStateRecord = BaseCollectionRecord & { id: typeof REVIEW_LAYOUT_RECORD_ID; treeWidth: number; treeCollapsed: boolean; viewMode: ReviewViewMode;};
type InlineDraftSide = "additions" | "deletions";
type InlineCommentDraftRecord = BaseCollectionRecord & { id: string; scopeId: string; path: string; line: number; side: InlineDraftSide; content: string;};
type InlineCommentActiveDraftRecord = BaseCollectionRecord & { id: string; scopeId: string; path: string; line: number; side: InlineDraftSide;};
type AppMetadataRecord = BaseCollectionRecord & { id: string; value: string;};
type AppCollectionBackendMode = "indexeddb" | "memory";
type TierDebugSummary = { count: number; approxBytes: number; oldestUpdatedAt: number | null; newestUpdatedAt: number | null;};
export type DataCollectionDebugSummary = { name: string; tier: StorageTier; count: number; approxBytes: number; oldestUpdatedAt: number | null; newestUpdatedAt: number | null; oldestExpiresAt: number | null; newestExpiresAt: number | null; expiredCount: number;};
export type DataCollectionsDebugSnapshot = { backendMode: AppCollectionBackendMode; persistenceDegraded: boolean; estimatedUsageBytes: number | null; estimatedQuotaBytes: number | null; totalRecords: number; totalBytes: number; lastSweepAt: number | null; tiers: Record<StorageTier, TierDebugSummary>; collections: DataCollectionDebugSummary[];};
let appDataReadyPromise: Promise<void> | null = null;let appDataDatabase: { close: () => Promise<boolean> } | null = null;let appDataFallbackActive = false;let appDataPersistenceDegraded = false;let lastAppDataSweepAt: number | null = null;
let appPreferencesCollection: Collection<AppPreferenceRecord, string> | null = null;let reviewViewedStateCollection: Collection<ReviewViewedStateRecord, string> | null = null;let reviewDirectoryStateCollection: Collection<ReviewDirectoryStateRecord, string> | null = null;let reviewLayoutStateCollection: Collection<ReviewLayoutStateRecord, string> | null = null;let inlineCommentDraftsCollection: Collection<InlineCommentDraftRecord, string> | null = null;let inlineCommentActiveDraftCollection: Collection<InlineCommentActiveDraftRecord, string> | null = null;let appMetadataCollection: Collection<AppMetadataRecord, string> | null = null;
function approxRecordBytes(record: object) { return new TextEncoder().encode(JSON.stringify(record)).length;}
function storageEstimate() { if (typeof navigator === "undefined" || !navigator.storage?.estimate) { return Promise.resolve({ usage: null, quota: null }); } return navigator.storage .estimate() .then((estimate) => ({ usage: typeof estimate.usage === "number" ? estimate.usage : null, quota: typeof estimate.quota === "number" ? estimate.quota : null, })) .catch(() => ({ usage: null, quota: null }));}
function stateExpiresAt(from: number) { return from + STATE_TTL_MS;}
function isExpiredRecord(record: { expiresAt?: number | null }, now: number) { return typeof record.expiresAt === "number" && record.expiresAt <= now;}
function createBaseSchema(maxLength = 300) { return { id: { type: "string", maxLength, }, updatedAt: { type: "number", minimum: 0, }, expiresAt: { type: ["number", "null"], }, } as const;}
const APP_PREFERENCES_SCHEMA = { title: "pullrequestdotreview app preferences", version: 0, type: "object", primaryKey: "id", properties: { ...createBaseSchema(120), value: { type: "object", additionalProperties: true, }, }, required: ["id", "updatedAt", "expiresAt", "value"], additionalProperties: false,} as const;
const REVIEW_VIEWED_STATE_SCHEMA = { title: "pullrequestdotreview review viewed state", version: 0, type: "object", primaryKey: "id", properties: { ...createBaseSchema(900), viewedVersionIds: { type: "array", items: { type: "string" }, }, }, required: ["id", "updatedAt", "expiresAt", "viewedVersionIds"], additionalProperties: false,} as const;
const REVIEW_DIRECTORY_STATE_SCHEMA = { title: "pullrequestdotreview review directory state", version: 0, type: "object", primaryKey: "id", properties: { ...createBaseSchema(900), expandedByPath: { type: "object", additionalProperties: { type: "boolean", }, }, }, required: ["id", "updatedAt", "expiresAt", "expandedByPath"], additionalProperties: false,} as const;
const REVIEW_LAYOUT_STATE_SCHEMA = { title: "pullrequestdotreview review layout state", version: 0, type: "object", primaryKey: "id", properties: { ...createBaseSchema(80), treeWidth: { type: "number" }, treeCollapsed: { type: "boolean" }, viewMode: { type: "string", maxLength: 20 }, }, required: ["id", "updatedAt", "expiresAt", "treeWidth", "treeCollapsed", "viewMode"], additionalProperties: false,} as const;
const INLINE_COMMENT_DRAFTS_SCHEMA = { title: "pullrequestdotreview inline comment drafts", version: 0, type: "object", primaryKey: "id", properties: { ...createBaseSchema(1600), scopeId: { type: "string", maxLength: 900 }, path: { type: "string", maxLength: 1000 }, line: { type: "number" }, side: { type: "string", maxLength: 20 }, content: { type: "string" }, }, required: ["id", "updatedAt", "expiresAt", "scopeId", "path", "line", "side", "content"], additionalProperties: false,} as const;
const INLINE_COMMENT_ACTIVE_DRAFT_SCHEMA = { title: "pullrequestdotreview inline comment active draft", version: 0, type: "object", primaryKey: "id", properties: { ...createBaseSchema(900), scopeId: { type: "string", maxLength: 900 }, path: { type: "string", maxLength: 1000 }, line: { type: "number" }, side: { type: "string", maxLength: 20 }, }, required: ["id", "updatedAt", "expiresAt", "scopeId", "path", "line", "side"], additionalProperties: false,} as const;
const APP_METADATA_SCHEMA = { title: "pullrequestdotreview app metadata", version: 0, type: "object", primaryKey: "id", properties: { ...createBaseSchema(120), value: { type: "string" }, }, required: ["id", "updatedAt", "expiresAt", "value"], additionalProperties: false,} as const;
function ensureCollectionsInitialized() { if ( appPreferencesCollection && reviewViewedStateCollection && reviewDirectoryStateCollection && reviewLayoutStateCollection && inlineCommentDraftsCollection && inlineCommentActiveDraftCollection && appMetadataCollection ) { return; }
appPreferencesCollection = createCollection( localOnlyCollectionOptions<AppPreferenceRecord, string>({ id: APP_PREFERENCES_COLLECTION_ID, getKey: (item) => item.id, }), );
reviewViewedStateCollection = createCollection( localOnlyCollectionOptions<ReviewViewedStateRecord, string>({ id: REVIEW_VIEWED_STATE_COLLECTION_ID, getKey: (item) => item.id, }), );
reviewDirectoryStateCollection = createCollection( localOnlyCollectionOptions<ReviewDirectoryStateRecord, string>({ id: REVIEW_DIRECTORY_STATE_COLLECTION_ID, getKey: (item) => item.id, }), );
reviewLayoutStateCollection = createCollection( localOnlyCollectionOptions<ReviewLayoutStateRecord, string>({ id: REVIEW_LAYOUT_STATE_COLLECTION_ID, getKey: (item) => item.id, }), );
inlineCommentDraftsCollection = createCollection( localOnlyCollectionOptions<InlineCommentDraftRecord, string>({ id: INLINE_COMMENT_DRAFTS_COLLECTION_ID, getKey: (item) => item.id, }), );
inlineCommentActiveDraftCollection = createCollection( localOnlyCollectionOptions<InlineCommentActiveDraftRecord, string>({ id: INLINE_COMMENT_ACTIVE_DRAFT_COLLECTION_ID, getKey: (item) => item.id, }), );
appMetadataCollection = createCollection( localOnlyCollectionOptions<AppMetadataRecord, string>({ id: APP_METADATA_COLLECTION_ID, getKey: (item) => item.id, }), );}
async function initRxdbCollections() { if (typeof window === "undefined") { ensureCollectionsInitialized(); appDataFallbackActive = true; return; }
const [{ createRxDatabase }, { getRxStorageDexie }] = await Promise.all([import("rxdb/plugins/core"), import("rxdb/plugins/storage-dexie")]);
const database = await createRxDatabase({ name: DATA_DATABASE_NAME, storage: getRxStorageDexie(), multiInstance: true, closeDuplicates: true, }); appDataDatabase = database;
const collectionDefinitions = { [APP_PREFERENCES_COLLECTION_NAME]: { schema: APP_PREFERENCES_SCHEMA, }, [REVIEW_VIEWED_STATE_COLLECTION_NAME]: { schema: REVIEW_VIEWED_STATE_SCHEMA, }, [REVIEW_DIRECTORY_STATE_COLLECTION_NAME]: { schema: REVIEW_DIRECTORY_STATE_SCHEMA, }, [REVIEW_LAYOUT_STATE_COLLECTION_NAME]: { schema: REVIEW_LAYOUT_STATE_SCHEMA, }, [INLINE_COMMENT_DRAFTS_COLLECTION_NAME]: { schema: INLINE_COMMENT_DRAFTS_SCHEMA, }, [INLINE_COMMENT_ACTIVE_DRAFT_COLLECTION_NAME]: { schema: INLINE_COMMENT_ACTIVE_DRAFT_SCHEMA, }, [APP_METADATA_COLLECTION_NAME]: { schema: APP_METADATA_SCHEMA, }, } as const;
for (const [collectionName, collectionSchema] of Object.entries(collectionDefinitions)) { const existingCollections = database.collections as Record<string, (typeof database.collections)[string]>; if (existingCollections[collectionName]) continue; try { await database.addCollections({ [collectionName]: collectionSchema, }); } catch (error) { if (!isRxErrorCode(error, "COL23")) { throw error; } } }
const collections = database.collections as Record<string, (typeof database.collections)[string]>; const missingCollectionNames = Object.keys(collectionDefinitions).filter((name) => !collections[name]); if (missingCollectionNames.length > 0) { throw new Error(`Data RxDB collections unavailable after init: ${missingCollectionNames.join(", ")}`); }
appPreferencesCollection = createCollection( rxdbCollectionOptions<AppPreferenceRecord>({ id: APP_PREFERENCES_COLLECTION_ID, rxCollection: collections[APP_PREFERENCES_COLLECTION_NAME], startSync: true, }), );
reviewViewedStateCollection = createCollection( rxdbCollectionOptions<ReviewViewedStateRecord>({ id: REVIEW_VIEWED_STATE_COLLECTION_ID, rxCollection: collections[REVIEW_VIEWED_STATE_COLLECTION_NAME], startSync: true, }), );
reviewDirectoryStateCollection = createCollection( rxdbCollectionOptions<ReviewDirectoryStateRecord>({ id: REVIEW_DIRECTORY_STATE_COLLECTION_ID, rxCollection: collections[REVIEW_DIRECTORY_STATE_COLLECTION_NAME], startSync: true, }), );
reviewLayoutStateCollection = createCollection( rxdbCollectionOptions<ReviewLayoutStateRecord>({ id: REVIEW_LAYOUT_STATE_COLLECTION_ID, rxCollection: collections[REVIEW_LAYOUT_STATE_COLLECTION_NAME], startSync: true, }), );
inlineCommentDraftsCollection = createCollection( rxdbCollectionOptions<InlineCommentDraftRecord>({ id: INLINE_COMMENT_DRAFTS_COLLECTION_ID, rxCollection: collections[INLINE_COMMENT_DRAFTS_COLLECTION_NAME], startSync: true, }), );
inlineCommentActiveDraftCollection = createCollection( rxdbCollectionOptions<InlineCommentActiveDraftRecord>({ id: INLINE_COMMENT_ACTIVE_DRAFT_COLLECTION_ID, rxCollection: collections[INLINE_COMMENT_ACTIVE_DRAFT_COLLECTION_NAME], startSync: true, }), );
appMetadataCollection = createCollection( rxdbCollectionOptions<AppMetadataRecord>({ id: APP_METADATA_COLLECTION_ID, rxCollection: collections[APP_METADATA_COLLECTION_NAME], startSync: true, }), );
await Promise.all([ appPreferencesCollection.preload(), reviewViewedStateCollection.preload(), reviewDirectoryStateCollection.preload(), reviewLayoutStateCollection.preload(), inlineCommentDraftsCollection.preload(), inlineCommentActiveDraftCollection.preload(), appMetadataCollection.preload(), ]);}
function isQuotaExceededError(error: unknown) { if (!error) return false; if (typeof DOMException !== "undefined" && error instanceof DOMException) { return error.name === "QuotaExceededError" || error.code === 22 || error.code === 1014; } if (error instanceof Error) { const message = error.message.toLowerCase(); return message.includes("quota") && message.includes("exceeded"); } return false;}
function isRxErrorCode(error: unknown, code: string) { if (!error || typeof error !== "object") return false; const value = error as { code?: string; message?: string }; if (value.code === code) return true; return typeof value.message === "string" && value.message.includes(code);}
function isTransientPersistenceError(error: unknown) { if (!error) return false; if (isRxErrorCode(error, "COL23") || isRxErrorCode(error, "DB8")) { return true; } if (error instanceof Error) { const message = error.message.toLowerCase(); return ( message.includes("closed") || message.includes("abort") || message.includes("aborted") || message.includes("is disposed") || message.includes("is destroyed") ); } return false;}
function markPersistenceIssue(error: unknown, context: string) { if (context.startsWith("delete:viewed:")) { return; } if (isTransientPersistenceError(error)) { return; } const firstIssue = !appDataPersistenceDegraded; appDataPersistenceDegraded = true; if (!firstIssue) return; if (isQuotaExceededError(error)) { console.warn(`Collection persistence quota exceeded during ${context}; keeping runtime state in memory.`, error); return; } console.warn(`Collection persistence degraded during ${context}; continuing with in-memory state.`);}
async function persistTransaction(persistPromise: Promise<unknown>, context: string) { try { await persistPromise; } catch (error) { markPersistenceIssue(error, context); }}
function deleteIndexedDbDatabase(name: string) { if (typeof indexedDB === "undefined") return Promise.resolve();
return new Promise<void>((resolve) => { const request = indexedDB.deleteDatabase(name); request.onsuccess = () => resolve(); request.onerror = () => resolve(); request.onblocked = () => resolve(); });}
async function clearLegacyLocalStorageKeys() { if (typeof window === "undefined") return; try { const keys: string[] = []; for (let index = 0; index < window.localStorage.length; index += 1) { const key = window.localStorage.key(index); if (!key || !key.startsWith(LOCAL_STORAGE_RESET_PREFIX)) continue; keys.push(key); }
for (const key of keys) { window.localStorage.removeItem(key); } } catch { // Ignore localStorage access issues. }}
async function upsertRecord<T extends { id: string }>(collection: Collection<T, string>, record: T, context: string) { try { const existing = collection.get(record.id); if (!existing) { const transaction = collection.insert(record); await persistTransaction(transaction.isPersisted.promise, `insert:${context}`); return; }
const transaction = collection.update(record.id, (draft) => { Object.assign(draft as Record<string, unknown>, record); }); await persistTransaction(transaction.isPersisted.promise, `update:${context}`); } catch (error) { markPersistenceIssue(error, `upsert:${context}`); }}
async function deleteRecord<T extends { id: string }>(collection: Collection<T, string>, id: string, context: string) { try { if (!collection.has(id)) return; const transaction = collection.delete(id); await persistTransaction(transaction.isPersisted.promise, `delete:${context}`); } catch (error) { markPersistenceIssue(error, `delete:${context}`); }}
function getAppPreferencesCollection() { ensureCollectionsInitialized(); if (!appPreferencesCollection) { throw new Error("App preferences collection is unavailable"); } return appPreferencesCollection;}
function readPermanentRecord<T extends Record<string, unknown>>(id: string): (T & BaseCollectionRecord & { id: string }) | null { const record = getAppPreferencesCollection().get(id); if (!record) return null; return { id: record.id, updatedAt: record.updatedAt, expiresAt: record.expiresAt, ...(record.value as T), };}
function writePermanentRecord(id: string, value: Record<string, unknown>, context: string) { const now = Date.now(); void upsertRecord( getAppPreferencesCollection(), { id, value, updatedAt: now, expiresAt: null, }, context, );}
function getReviewViewedStateCollection() { ensureCollectionsInitialized(); if (!reviewViewedStateCollection) { throw new Error("Review viewed state collection is unavailable"); } return reviewViewedStateCollection;}
function getReviewDirectoryStateCollection() { ensureCollectionsInitialized(); if (!reviewDirectoryStateCollection) { throw new Error("Review directory state collection is unavailable"); } return reviewDirectoryStateCollection;}
function getReviewLayoutStateCollection() { ensureCollectionsInitialized(); if (!reviewLayoutStateCollection) { throw new Error("Review layout state collection is unavailable"); } return reviewLayoutStateCollection;}
function getInlineCommentDraftsCollection() { ensureCollectionsInitialized(); if (!inlineCommentDraftsCollection) { throw new Error("Inline comment drafts collection is unavailable"); } return inlineCommentDraftsCollection;}
function getInlineCommentActiveDraftCollection() { ensureCollectionsInitialized(); if (!inlineCommentActiveDraftCollection) { throw new Error("Inline comment active draft collection is unavailable"); } return inlineCommentActiveDraftCollection;}
function getAppMetadataCollection() { ensureCollectionsInitialized(); if (!appMetadataCollection) { throw new Error("App metadata collection is unavailable"); } return appMetadataCollection;}
async function runLegacyResetIfNeeded() { const metadataCollection = getAppMetadataCollection(); const marker = metadataCollection.get(LEGACY_RESET_METADATA_ID); if (marker?.value === "done") { return; }
await Promise.all([deleteIndexedDbDatabase("pullrequestdotreview_settings"), deleteIndexedDbDatabase("pullrequestdotreview_host_data_v4")]); await clearLegacyLocalStorageKeys();
const now = Date.now(); await upsertRecord( metadataCollection, { id: LEGACY_RESET_METADATA_ID, value: "done", updatedAt: now, expiresAt: null, }, LEGACY_RESET_METADATA_ID, );}
export function ensureDataCollectionsReady() { if (!appDataReadyPromise) { appDataReadyPromise = initRxdbCollections() .catch((error) => { console.error("Failed to initialize data collections in IndexedDB, falling back to in-memory collections.", error); ensureCollectionsInitialized(); appDataFallbackActive = true; }) .then(async () => { await runLegacyResetIfNeeded(); await sweepExpiredStateCollections(); }); }
return appDataReadyPromise;}
function normalizeReposByHost(reposByHost: Record<GitHost, RepoRef[]>): Record<GitHost, RepoRef[]> { const normalizeHostRepos = (host: GitHost, repos: RepoRef[]) => { const deduped = new Map<string, RepoRef>(); for (const repo of repos) { if (!repo || repo.host !== host) continue; const workspace = repo.workspace.trim(); const repositorySlug = repo.repo.trim(); if (!workspace || !repositorySlug) continue; const fullName = typeof repo.fullName === "string" && repo.fullName.trim().length > 0 ? repo.fullName.trim() : `${workspace}/${repositorySlug}`; const displayName = typeof repo.displayName === "string" && repo.displayName.trim().length > 0 ? repo.displayName.trim() : repositorySlug; const normalized: RepoRef = { host, workspace, repo: repositorySlug, fullName, displayName, }; deduped.set(`${host}:${fullName}`, normalized); } return Array.from(deduped.values()).sort((a, b) => a.fullName.localeCompare(b.fullName)); };
return { bitbucket: normalizeHostRepos("bitbucket", reposByHost.bitbucket ?? []), github: normalizeHostRepos("github", reposByHost.github ?? []), };}
export function readAppearanceSettingsRecord() { return readPermanentRecord<Omit<AppearanceSettingsRecord, keyof BaseCollectionRecord | "id">>(APPEARANCE_RECORD_ID) as AppearanceSettingsRecord | null;}
export function writeAppearanceSettingsRecord(settings: Omit<AppearanceSettingsRecord, "id" | "updatedAt" | "expiresAt">) { writePermanentRecord(APPEARANCE_RECORD_ID, settings as Record<string, unknown>, APPEARANCE_RECORD_ID);}
export function readDiffOptionsRecord() { return readPermanentRecord<Omit<DiffOptionsRecord, keyof BaseCollectionRecord | "id">>(DIFF_OPTIONS_RECORD_ID) as DiffOptionsRecord | null;}
export function writeDiffOptionsRecord(options: Omit<DiffOptionsRecord, "id" | "updatedAt" | "expiresAt">) { writePermanentRecord(DIFF_OPTIONS_RECORD_ID, options as Record<string, unknown>, DIFF_OPTIONS_RECORD_ID);}
export function readTreeSettingsRecord() { return readPermanentRecord<Omit<TreeSettingsRecord, keyof BaseCollectionRecord | "id">>(TREE_SETTINGS_RECORD_ID) as TreeSettingsRecord | null;}
export function writeTreeSettingsRecord(settings: Omit<TreeSettingsRecord, "id" | "updatedAt" | "expiresAt">) { writePermanentRecord(TREE_SETTINGS_RECORD_ID, settings as Record<string, unknown>, TREE_SETTINGS_RECORD_ID);}
export function readShortcutsRecord() { return readPermanentRecord<Omit<ShortcutsRecord, keyof BaseCollectionRecord | "id">>(SHORTCUTS_RECORD_ID) as ShortcutsRecord | null;}
export function writeShortcutsRecord(shortcuts: Omit<ShortcutsRecord, "id" | "updatedAt" | "expiresAt">) { writePermanentRecord(SHORTCUTS_RECORD_ID, shortcuts as Record<string, unknown>, SHORTCUTS_RECORD_ID);}
export function readHostPreferencesRecord() { return readPermanentRecord<Omit<HostPreferencesRecord, keyof BaseCollectionRecord | "id">>(HOST_PREFERENCES_RECORD_ID) as HostPreferencesRecord | null;}
export function writeHostPreferencesRecord(data: { activeHost: GitHost; reposByHost: Record<GitHost, RepoRef[]> }) { writePermanentRecord( HOST_PREFERENCES_RECORD_ID, { activeHost: data.activeHost, reposByHost: normalizeReposByHost(data.reposByHost), }, HOST_PREFERENCES_RECORD_ID, );}
export function readBitbucketAuthCredential() { const record = readPermanentRecord<Omit<BitbucketAuthCredentialRecord, keyof BaseCollectionRecord | "id">>("bitbucket"); if (!record || record.host !== "bitbucket") return null; if (typeof record.email !== "string" || typeof record.apiToken !== "string") return null; return { email: record.email, apiToken: record.apiToken, };}
export function writeBitbucketAuthCredential(data: { email: string; apiToken: string }) { writePermanentRecord( "bitbucket", { host: "bitbucket", email: data.email, apiToken: data.apiToken, }, "auth:bitbucket", );}
export function clearBitbucketAuthCredential() { void deleteRecord(getAppPreferencesCollection(), "bitbucket", "auth:bitbucket");}
export function readGithubAuthCredential() { const record = readPermanentRecord<Omit<GithubAuthCredentialRecord, keyof BaseCollectionRecord | "id">>("github"); if (!record || record.host !== "github") return null; if (typeof record.token !== "string") return null; return { token: record.token, };}
export function writeGithubAuthCredential(data: { token: string }) { writePermanentRecord( "github", { host: "github", token: data.token, }, "auth:github", );}
export function clearGithubAuthCredential() { void deleteRecord(getAppPreferencesCollection(), "github", "auth:github");}
function readStateRecord<T extends { expiresAt: number | null; id: string }>(collection: Collection<T, string>, id: string) { const record = collection.get(id); if (!record) return null; if (isExpiredRecord(record, Date.now())) { void deleteRecord(collection, id, id); return null; } return record;}
export function readReviewViewedVersionIds(scopeId: string) { if (!scopeId) return new Set<string>(); const record = readStateRecord(getReviewViewedStateCollection(), scopeId); if (!record) return new Set<string>(); return new Set(record.viewedVersionIds);}
export function writeReviewViewedVersionIds(scopeId: string, viewedVersionIds: Set<string>) { if (!scopeId) return; if (viewedVersionIds.size === 0) { void deleteRecord(getReviewViewedStateCollection(), scopeId, `viewed:${scopeId}`); return; }
const now = Date.now(); void upsertRecord( getReviewViewedStateCollection(), { id: scopeId, viewedVersionIds: Array.from(viewedVersionIds), updatedAt: now, expiresAt: stateExpiresAt(now), }, `viewed:${scopeId}`, );}
export function readReviewDirectoryState(scopeId: string) { if (!scopeId) return null; const record = readStateRecord(getReviewDirectoryStateCollection(), scopeId); if (!record) return null; return { ...record.expandedByPath };}
export function writeReviewDirectoryState(scopeId: string, expandedByPath: Record<string, boolean>) { if (!scopeId) return; const now = Date.now(); void upsertRecord( getReviewDirectoryStateCollection(), { id: scopeId, expandedByPath, updatedAt: now, expiresAt: stateExpiresAt(now), }, `directory:${scopeId}`, );}
export function readReviewLayoutState() { return readStateRecord(getReviewLayoutStateCollection(), REVIEW_LAYOUT_RECORD_ID);}
export function writeReviewLayoutState(data: Omit<ReviewLayoutStateRecord, "id" | "updatedAt" | "expiresAt">) { const now = Date.now(); void upsertRecord( getReviewLayoutStateCollection(), { id: REVIEW_LAYOUT_RECORD_ID, ...data, updatedAt: now, expiresAt: stateExpiresAt(now), }, REVIEW_LAYOUT_RECORD_ID, );}
type InlineCommentDraftLocation = { path: string; line: number; side: InlineDraftSide;};
function inlineDraftRecordId(scopeId: string, draft: InlineCommentDraftLocation) { return `${scopeId}:${draft.side}:${draft.line}:${encodeURIComponent(draft.path)}`;}
export function readInlineCommentDraftContent(scopeId: string, draft: InlineCommentDraftLocation) { if (!scopeId) return ""; const record = readStateRecord(getInlineCommentDraftsCollection(), inlineDraftRecordId(scopeId, draft)); return record?.content ?? "";}
export function writeInlineCommentDraftContent(scopeId: string, draft: InlineCommentDraftLocation, content: string) { if (!scopeId) return; const draftCollection = getInlineCommentDraftsCollection(); const draftId = inlineDraftRecordId(scopeId, draft);
if (!content.trim()) { void deleteRecord(draftCollection, draftId, draftId); return; }
const now = Date.now(); void upsertRecord( draftCollection, { id: draftId, scopeId, path: draft.path, line: draft.line, side: draft.side, content, updatedAt: now, expiresAt: stateExpiresAt(now), }, draftId, );}
export function clearInlineCommentDraftContent(scopeId: string, draft: InlineCommentDraftLocation) { if (!scopeId) return; void deleteRecord(getInlineCommentDraftsCollection(), inlineDraftRecordId(scopeId, draft), inlineDraftRecordId(scopeId, draft));}
export function readInlineCommentActiveDraft(scopeId: string): InlineCommentDraftLocation | null { if (!scopeId) return null; const record = readStateRecord(getInlineCommentActiveDraftCollection(), scopeId); if (!record) return null; return { path: record.path, line: record.line, side: record.side, };}
export function writeInlineCommentActiveDraft(scopeId: string, draft: InlineCommentDraftLocation) { if (!scopeId) return; const now = Date.now(); void upsertRecord( getInlineCommentActiveDraftCollection(), { id: scopeId, scopeId, path: draft.path, line: draft.line, side: draft.side, updatedAt: now, expiresAt: stateExpiresAt(now), }, `inline-active:${scopeId}`, );}
export function clearInlineCommentActiveDraft(scopeId: string) { if (!scopeId) return; void deleteRecord(getInlineCommentActiveDraftCollection(), scopeId, `inline-active:${scopeId}`);}
export function listInlineCommentDrafts(scopeId: string): Array<InlineCommentDraftLocation & { content: string; updatedAt: number }> { if (!scopeId) return []; const now = Date.now(); const results: Array<InlineCommentDraftLocation & { content: string; updatedAt: number }> = [];
for (const record of getInlineCommentDraftsCollection().values()) { if (record.scopeId !== scopeId) continue; if (isExpiredRecord(record, now)) { void deleteRecord(getInlineCommentDraftsCollection(), record.id, record.id); continue; } if (!record.content.trim()) continue;
results.push({ path: record.path, line: record.line, side: record.side, content: record.content, updatedAt: record.updatedAt, }); }
results.sort((a, b) => b.updatedAt - a.updatedAt); return results;}
async function sweepExpiredCollection<T extends { id: string; expiresAt: number | null }>(collection: Collection<T, string>, now: number, label: string) { let removed = 0; for (const record of collection.values()) { if (!isExpiredRecord(record, now)) continue; await deleteRecord(collection, record.id, `${label}:${record.id}`); removed += 1; } return removed;}
async function sweepExpiredStateCollections(now = Date.now()) { ensureCollectionsInitialized(); let removed = 0; removed += await sweepExpiredCollection(getReviewViewedStateCollection(), now, "viewed"); removed += await sweepExpiredCollection(getReviewDirectoryStateCollection(), now, "directory"); removed += await sweepExpiredCollection(getReviewLayoutStateCollection(), now, "layout"); removed += await sweepExpiredCollection(getInlineCommentDraftsCollection(), now, "inline-draft"); removed += await sweepExpiredCollection(getInlineCommentActiveDraftCollection(), now, "inline-active"); lastAppDataSweepAt = now; return { removed };}
type AppCollectionSummary = { name: string; tier: StorageTier; collection: Collection<BaseCollectionRecord, string>;};
function getAppCollectionSummaries(): AppCollectionSummary[] { return [ { name: "appPreferences", tier: "permanent", collection: getAppPreferencesCollection() as Collection<BaseCollectionRecord, string> }, { name: "reviewViewedState", tier: "state", collection: getReviewViewedStateCollection() as Collection<BaseCollectionRecord, string> }, { name: "reviewDirectoryState", tier: "state", collection: getReviewDirectoryStateCollection() as Collection<BaseCollectionRecord, string> }, { name: "reviewLayoutState", tier: "state", collection: getReviewLayoutStateCollection() as Collection<BaseCollectionRecord, string> }, { name: "inlineCommentDrafts", tier: "state", collection: getInlineCommentDraftsCollection() as Collection<BaseCollectionRecord, string> }, { name: "inlineCommentActiveDraft", tier: "state", collection: getInlineCommentActiveDraftCollection() as Collection<BaseCollectionRecord, string> }, ];}
export async function getDataCollectionsDebugSnapshot(now = Date.now()): Promise<DataCollectionsDebugSnapshot> { ensureCollectionsInitialized();
const tiers: Record<StorageTier, TierDebugSummary> = { state: { count: 0, approxBytes: 0, oldestUpdatedAt: null, newestUpdatedAt: null }, permanent: { count: 0, approxBytes: 0, oldestUpdatedAt: null, newestUpdatedAt: null }, };
const collections: DataCollectionDebugSummary[] = []; let totalRecords = 0; let totalBytes = 0;
for (const summary of getAppCollectionSummaries()) { const entry: DataCollectionDebugSummary = { name: summary.name, tier: summary.tier, count: 0, approxBytes: 0, oldestUpdatedAt: null, newestUpdatedAt: null, oldestExpiresAt: null, newestExpiresAt: null, expiredCount: 0, };
for (const record of summary.collection.values()) { entry.count += 1; const bytes = approxRecordBytes(record); entry.approxBytes += bytes;
entry.oldestUpdatedAt = entry.oldestUpdatedAt === null ? record.updatedAt : Math.min(entry.oldestUpdatedAt, record.updatedAt); entry.newestUpdatedAt = entry.newestUpdatedAt === null ? record.updatedAt : Math.max(entry.newestUpdatedAt, record.updatedAt);
if (typeof record.expiresAt === "number") { entry.oldestExpiresAt = entry.oldestExpiresAt === null ? record.expiresAt : Math.min(entry.oldestExpiresAt, record.expiresAt); entry.newestExpiresAt = entry.newestExpiresAt === null ? record.expiresAt : Math.max(entry.newestExpiresAt, record.expiresAt); if (record.expiresAt <= now) { entry.expiredCount += 1; } } }
totalRecords += entry.count; totalBytes += entry.approxBytes; tiers[summary.tier].count += entry.count; tiers[summary.tier].approxBytes += entry.approxBytes; const tierSummary = tiers[summary.tier]; const tierOldest = tierSummary.oldestUpdatedAt; const tierNewest = tierSummary.newestUpdatedAt; tierSummary.oldestUpdatedAt = tierOldest === null ? entry.oldestUpdatedAt : entry.oldestUpdatedAt === null ? tierOldest : Math.min(tierOldest, entry.oldestUpdatedAt); tierSummary.newestUpdatedAt = tierNewest === null ? entry.newestUpdatedAt : entry.newestUpdatedAt === null ? tierNewest : Math.max(tierNewest, entry.newestUpdatedAt);
collections.push(entry); }
collections.sort((a, b) => a.name.localeCompare(b.name));
const estimate = await storageEstimate();
return { backendMode: appDataFallbackActive ? "memory" : "indexeddb", persistenceDegraded: appDataPersistenceDegraded, estimatedUsageBytes: estimate.usage, estimatedQuotaBytes: estimate.quota, totalRecords, totalBytes, lastSweepAt: lastAppDataSweepAt, tiers, collections, };}
export async function clearExpiredDataNow(now = Date.now()) { const appResult = await sweepExpiredStateCollections(now); return { removed: appResult.removed, appRemoved: appResult.removed, };}
async function __resetDataCollectionsForTests() { if (appDataDatabase) { await appDataDatabase.close(); }
appDataDatabase = null; appDataReadyPromise = null; appDataFallbackActive = false; appDataPersistenceDegraded = false; lastAppDataSweepAt = null;
appPreferencesCollection = null; reviewViewedStateCollection = null; reviewDirectoryStateCollection = null; reviewLayoutStateCollection = null; inlineCommentDraftsCollection = null; inlineCommentActiveDraftCollection = null; appMetadataCollection = null;}