1import {2activateDraft,3createDraft,4draftLimits,5restoreDraftWorkspace,6removeDraft,7restoreDraftRemoval,8restoreRemovedDraft,9updateDraft,10typeDraft,11typeDraftWorkspace,12typeDraftRemoval,13} from"./drafts.ts";14importtype { Composition } from"./composition.ts";1516exportconstdraftStorageKey="axiomatic-drafts:v1";17exportconstdraftRemovalKey="axiomatic-last-removal:v1";18exportclassDraftConflictextendsError {}19exportclassDraftRemovalReplacementextendsError {}2021exportinterfaceRemovalStorage {22read():string|null;23write(value:string|null):void;24}25constbrowserRemoval:RemovalStorage= {26read: () =>sessionStorage.getItem(draftRemovalKey),27write: (value) => {28if (value===null) sessionStorage.removeItem(draftRemovalKey);29elsesessionStorage.setItem(draftRemovalKey, value);30 },31};3233exportinterfaceDraftStorageEnvironment {34read():string|null;35write(value:string):void;36exclusive<T>(action: () =>T):Promise<T>;37}38constbrowserStorage:DraftStorageEnvironment= {39read: () =>localStorage.getItem(draftStorageKey),40write: (value) =>localStorage.setItem(draftStorageKey, value),41exclusive: (action) => {42if (!navigator.locks)43returnPromise.reject(44newError(45"Saving drafts needs HTTPS or localhost in a modern browser.",46 ),47 );48returnnavigator.locks.request(draftStorageKey, action);49 },50};5152/** Native locks serialize the read/check/write across tabs. Comparing the53 * saved draft with our base prevents a stale editor from overwriting it. */54exportclassDraftStorage {55privatereadonlyenvironment:DraftStorageEnvironment;56privatereadonlyremoval:RemovalStorage;57constructor(58environment:DraftStorageEnvironment=browserStorage,59removal:RemovalStorage=browserRemoval,60 ) {61this.environment=environment;62this.removal=removal;63 }64read():DraftWorkspace|undefined {65constraw=this.environment.read();66if (raw===null) returnundefined;67if (raw.length>draftLimits.characters)68thrownewError("Stored drafts are too large to open.");69constvalue=restoreDraftWorkspace(JSON.parse(raw));70if (!value)71thrownewError(72"Stored drafts could not be read. They have been left unchanged.",73 );74returnvalue;75 }7677privatewrite(value:DraftWorkspace):DraftWorkspace {78constrestored=restoreDraftWorkspace(value);79if (!restored)80thrownewError(81"These drafts are too large to save. Your previous saved work is unchanged.",82 );83this.environment.write(JSON.stringify(restored));84returnrestored;85 }8687privatelocked<T>(action: () =>T):Promise<T> {88returnthis.environment.exclusive(action);89 }9091create(92tree:Composition,93name:string,94state?:Pick<Draft, "copy"|"width">,95 ):Promise<DraftWorkspace> {96returnthis.locked(() => {97constworkspace=this.read();98constnames=newSet(workspace?.drafts.map((draft) =>draft.name));99conststem= (name.trim() ||"Untitled composition").slice(0, 72);100let unique =stem;101for (letindex=2; names.has(unique); index++)102 unique =`${stem} (${index})`;103constid=crypto.randomUUID();104letnext=createDraft(workspace, tree, unique, id);105if (state) next=updateDraft(next, id, state.copy, state.width, unique);106returnthis.write(next);107 });108 }109110save(draft:Draft, base:Draft|undefined):Promise<DraftWorkspace> {111returnthis.locked(() => {112constworkspace=this.read();113constcurrent=workspace?.drafts.find((item) =>item.id===draft.id);114if (115!workspace||116!base||117JSON.stringify(current) !==JSON.stringify(base)118 )119thrownewDraftConflict(120current121?"This draft changed in another tab. Your edits here are still available."122:"This draft was removed in another tab. Your edits here are still available to save as a new draft.",123 );124returnthis.write(125updateDraft(workspace, draft.id, draft.copy, draft.width, draft.name),126 );127 });128 }129130activate(id:string):Promise<DraftWorkspace> {131returnthis.locked(() => {132constworkspace=this.read();133if (!workspace)134thrownewError("This saved draft is no longer available.");135returnthis.write(activateDraft(workspace, id));136 });137 }138139lastRemoval():DraftRemoval|undefined {140constraw=this.removal.read();141if (raw===null) returnundefined;142if (raw.length>draftLimits.characters)143thrownewError("The removed draft could not be read.");144constvalue:unknown=JSON.parse(raw);145constrestored=146value&&147typeofvalue==="object"&&148"version"invalue&&149value.version===1150?restoreDraftRemoval(value)151:undefined;152if (!restored) thrownewError("The removed draft could not be read.");153// A successful restoration is durable even if clearing its receipt failed.154letworkspace:DraftWorkspace|undefined;155try {156workspace=this.read();157 } catch {158// The receipt is readable even if durable storage is not. Restoration159// still refuses to replace unreadable work inside the locked transaction.160 }161if (workspace?.drafts.some((draft) =>draft.id===restored.draft.id))162returnundefined;163returnrestored;164 }165166remove(base:Draft, replaceBlockedRemoval=false):Promise<DraftWorkspace> {167returnthis.locked(() => {168constworkspace=this.read();169constcurrent=workspace?.drafts.find((draft) =>draft.id===base.id);170if (!workspace||JSON.stringify(current) !==JSON.stringify(base))171thrownewDraftConflict(172current173?"This draft changed in another tab. Your draft has not been removed."174:"This draft was already removed in another tab. Your work here is still available.",175 );176constresult=removeDraft(workspace, base.id);177letpreviousRemoval:DraftRemoval|undefined;178try {179previousRemoval=this.lastRemoval();180 } catch {181if (!replaceBlockedRemoval)182thrownewDraftRemovalReplacement(183`The previous Undo removal entry cannot be read. Removing “${base.name|| "Untitled composition"}” will replace it.`,184 );185 }186if (previousRemoval&&!replaceBlockedRemoval) {187try {188restoreRemovedDraft(workspace, previousRemoval);189 } catch {190thrownewDraftRemovalReplacement(191`“${previousRemoval.draft.name|| "Untitled composition"}” cannot currently be restored. Removing “${base.name|| "Untitled composition"}” will replace its Undo removal entry.`,192 );193 }194 }195constprevious=this.removal.read();196// Save the recovery copy before deleting anything durable. A refusal197// leaves both the workspace and the previous removal unchanged.198this.removal.write(JSON.stringify({ version: 1, ...result.removed }));199try {200returnthis.write(result.workspace);201 } catch (error) {202try {203this.removal.write(previous);204 } catch (rollbackError) {205thrownewAggregateError(206 [error, rollbackError],207"The draft was not removed. Storage also refused to recover the previous Undo removal entry.",208 );209 }210throwerror;211 }212 });213 }214215undoRemoval():Promise<DraftWorkspace> {216returnthis.locked(() => {217constremoved=this.lastRemoval();218if (!removed)219thrownewError("There is no removed draft to restore in this tab.");220constworkspace=this.write(restoreRemovedDraft(this.read(), removed));221try {222this.removal.write(null);223 } catch {224// The saved draft is authoritative; lastRemoval ignores its old receipt.225 }226returnworkspace;227 });228 }229}