@jxsuite/server 9.2.1 → 9.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,231 @@
1
+ /**
2
+ * The live preview overlay as the project state host owns it (`specs/project-state.md` §11.3): the
3
+ * unsaved bytes each client publishes for a document, keyed by the document's {@link DocId} and the
4
+ * client that set them rather than by a path or a connection.
5
+ *
6
+ * A rename or a move keeps the overlay and republishes it at the new path; a removal drops it,
7
+ * matched by its path as well as its id, so an overlay keyed before the host knew the document or
8
+ * by an id from an earlier epoch (a restart mints new ones) is dropped with its file too. A
9
+ * client's overlays outlive its socket: the host drops them once no subscription naming that
10
+ * `clientId` has been open for the grace period (`overlayGraceMs`, 30 seconds by default), so a
11
+ * reconnect, a suspended window or a host restart never unpublishes an author's preview, and a
12
+ * closed window never leaves its bytes published for longer than that. A client that named no
13
+ * `clientId` has its overlays dropped when its subscription ends.
14
+ *
15
+ * The registry performs no I/O: it tells `publish` and `unpublish` what a reader should see at a
16
+ * path, and the host hands it the file events it emits (`apply`). Two clients may overlay one
17
+ * document; the one that set it last is what a reader sees, and clearing it shows the other's.
18
+ *
19
+ * @module
20
+ */
21
+
22
+ import type { DocId, ProjectEvent } from "@jxsuite/protocol/project-state";
23
+
24
+ /** The default grace before a departed client's overlays are dropped, in ms (§11.3). */
25
+ export const OVERLAY_GRACE_MS = 30_000;
26
+
27
+ export interface OverlayRegistryOptions {
28
+ /** Show `contents` to readers of `path` in place of the file. */
29
+ publish: (path: string, contents: string) => void;
30
+ /** Show readers the file at `path` again. */
31
+ unpublish: (path: string) => void;
32
+ /** How long a client's overlays outlive its last subscription, in ms. */
33
+ graceMs?: number;
34
+ }
35
+
36
+ /** Who set an overlay: a client by its `clientId`, or a subscription that named none. */
37
+ export type OverlayOwner = { clientId: string } | { anonymous: string };
38
+
39
+ export interface OverlayRegistry {
40
+ /** Publish `owner`'s unsaved bytes for the document `docId`, which is at `path` now. */
41
+ set: (owner: OverlayOwner, docId: DocId, path: string, contents: string) => void;
42
+ /** Drop `owner`'s overlay of `docId`, or every overlay it set. */
43
+ clear: (owner: OverlayOwner, docId?: DocId) => void;
44
+ /** Drop every overlay, whoever set it. */
45
+ clearAll: () => void;
46
+ /** A subscription for `owner` opened: its overlays are kept for as long as one is open. */
47
+ opened: (owner: OverlayOwner) => void;
48
+ /** A subscription for `owner` ended; the last one starts its grace (none for an anonymous one). */
49
+ closed: (owner: OverlayOwner) => void;
50
+ /** Follow the host's file events: a rename moves an overlay, a removal drops it. */
51
+ apply: (events: readonly ProjectEvent[]) => void;
52
+ /**
53
+ * Hand `from`'s layer of each document in `docIds` to `to`, keeping what readers see: a socket
54
+ * that subscribes takes over what it set before it did (§11.3).
55
+ */
56
+ adopt: (from: OverlayOwner, to: OverlayOwner, docIds: Iterable<DocId>) => void;
57
+ /** The documents overlaid now, with the path each is published at. */
58
+ published: () => { docId: DocId; path: string }[];
59
+ /** Cancel every pending grace, and arm none after; the overlays stay as they are. */
60
+ close: () => void;
61
+ }
62
+
63
+ interface Overlaid {
64
+ path: string;
65
+ /** Each owner's bytes, the most recently set last. */
66
+ layers: Map<string, string>;
67
+ }
68
+
69
+ const keyOf = (owner: OverlayOwner): string =>
70
+ "clientId" in owner ? `client:${owner.clientId}` : `anonymous:${owner.anonymous}`;
71
+
72
+ /** Whether `path` is `dir` or beneath it. */
73
+ const within = (path: string, dir: string): boolean => path === dir || path.startsWith(`${dir}/`);
74
+
75
+ /** Create an empty overlay registry. */
76
+ export function createOverlayRegistry(options: OverlayRegistryOptions): OverlayRegistry {
77
+ const graceMs = options.graceMs ?? OVERLAY_GRACE_MS;
78
+ const docs = new Map<DocId, Overlaid>();
79
+ const open = new Map<string, number>();
80
+ const graces = new Map<string, ReturnType<typeof setTimeout>>();
81
+ let stopped = false;
82
+
83
+ /** Show readers of `doc` the newest layer, or the file when there is none. */
84
+ const show = (docId: DocId, doc: Overlaid): void => {
85
+ const newest = [...doc.layers.values()].at(-1);
86
+ if (newest === undefined) {
87
+ docs.delete(docId);
88
+ options.unpublish(doc.path);
89
+ } else {
90
+ options.publish(doc.path, newest);
91
+ }
92
+ };
93
+
94
+ const dropOwner = (key: string): void => {
95
+ for (const [docId, doc] of docs) {
96
+ if (doc.layers.delete(key)) {
97
+ show(docId, doc);
98
+ }
99
+ }
100
+ };
101
+
102
+ const cancelGrace = (key: string): void => {
103
+ const timer = graces.get(key);
104
+ if (timer !== undefined) {
105
+ clearTimeout(timer);
106
+ graces.delete(key);
107
+ }
108
+ };
109
+
110
+ const move = (from: string, to: string): void => {
111
+ for (const doc of docs.values()) {
112
+ if (within(doc.path, from)) {
113
+ const moved = `${to}${doc.path.slice(from.length)}`;
114
+ options.unpublish(doc.path);
115
+ doc.path = moved;
116
+ options.publish(moved, [...doc.layers.values()].at(-1)!);
117
+ }
118
+ }
119
+ };
120
+
121
+ const drop = (docId: DocId, path: string, isDir: boolean): void => {
122
+ for (const [id, doc] of docs) {
123
+ if (id === docId || (isDir ? within(doc.path, path) : doc.path === path)) {
124
+ docs.delete(id);
125
+ options.unpublish(doc.path);
126
+ }
127
+ }
128
+ };
129
+
130
+ return {
131
+ adopt(from, to, docIds) {
132
+ const fromKey = keyOf(from);
133
+ const toKey = keyOf(to);
134
+ for (const docId of docIds) {
135
+ const doc = docs.get(docId);
136
+ if (doc === undefined || !doc.layers.has(fromKey)) {
137
+ continue;
138
+ }
139
+ const keys = [...doc.layers.keys()];
140
+ if (keys.indexOf(toKey) > keys.indexOf(fromKey)) {
141
+ // `to` set the document since: its own layer is the newer one.
142
+ doc.layers.delete(fromKey);
143
+ } else {
144
+ // Rebuilt in order, so the layer keeps its place and what readers see does not move.
145
+ doc.layers = new Map(
146
+ [...doc.layers].flatMap(([key, value]): [string, string][] =>
147
+ key === toKey ? [] : [[key === fromKey ? toKey : key, value]],
148
+ ),
149
+ );
150
+ }
151
+ }
152
+ },
153
+ apply(events) {
154
+ for (const event of events) {
155
+ if (event.type === "fileRenamed") {
156
+ move(event.from, event.to);
157
+ } else if (event.type === "fileRemoved") {
158
+ drop(event.docId, event.path, event.isDir);
159
+ }
160
+ }
161
+ },
162
+ clear(owner, docId) {
163
+ const key = keyOf(owner);
164
+ if (docId === undefined) {
165
+ dropOwner(key);
166
+ return;
167
+ }
168
+ const doc = docs.get(docId);
169
+ if (doc?.layers.delete(key) === true) {
170
+ show(docId, doc);
171
+ }
172
+ },
173
+ clearAll() {
174
+ for (const doc of docs.values()) {
175
+ options.unpublish(doc.path);
176
+ }
177
+ docs.clear();
178
+ },
179
+ close() {
180
+ stopped = true;
181
+ for (const timer of graces.values()) {
182
+ clearTimeout(timer);
183
+ }
184
+ graces.clear();
185
+ },
186
+ closed(owner) {
187
+ const key = keyOf(owner);
188
+ const count = (open.get(key) ?? 1) - 1;
189
+ if (count > 0) {
190
+ open.set(key, count);
191
+ return;
192
+ }
193
+ open.delete(key);
194
+ if (!("clientId" in owner)) {
195
+ dropOwner(key);
196
+ return;
197
+ }
198
+ cancelGrace(key);
199
+ if (stopped) {
200
+ return;
201
+ }
202
+ const timer = setTimeout(() => {
203
+ graces.delete(key);
204
+ dropOwner(key);
205
+ }, graceMs);
206
+ // A pending grace must not keep the process alive on its own.
207
+ timer.unref();
208
+ graces.set(key, timer);
209
+ },
210
+ opened(owner) {
211
+ const key = keyOf(owner);
212
+ cancelGrace(key);
213
+ open.set(key, (open.get(key) ?? 0) + 1);
214
+ },
215
+ published: () => [...docs].map(([docId, doc]) => ({ docId, path: doc.path })),
216
+ set(owner, docId, path, contents) {
217
+ const key = keyOf(owner);
218
+ let doc = docs.get(docId);
219
+ if (doc === undefined) {
220
+ doc = { layers: new Map(), path };
221
+ docs.set(docId, doc);
222
+ } else if (doc.path !== path) {
223
+ options.unpublish(doc.path);
224
+ doc.path = path;
225
+ }
226
+ doc.layers.delete(key);
227
+ doc.layers.set(key, contents);
228
+ options.publish(path, contents);
229
+ },
230
+ };
231
+ }
@@ -0,0 +1,473 @@
1
+ /**
2
+ * The rename cascade (`specs/project-state.md` §9): one {@link RenameOperation} that moves a file or
3
+ * a directory and rewrites every reference to it, planned before the disk is touched and applied
4
+ * from an outbox that undoes its completed steps when a later one fails.
5
+ *
6
+ * The planning half is the refactor engine's (`planRename`, `../refactor/apply.ts`), run before the
7
+ * move over the documents the dependency graph says may reference what moves (§8), the project
8
+ * configuration (whose references are not graph edges), and every document the host could not
9
+ * index. Each rewrite names the hash of the bytes it was planned from, so a referrer that changed
10
+ * between planning and applying refuses its step and rolls the operation back (§5).
11
+ *
12
+ * The outbox is in memory: a crash mid-operation leaves the steps already applied, and the host's
13
+ * next start reports them as external changes. A durable outbox waits for §13.
14
+ *
15
+ * This module holds no state and touches no disk itself; the host hands it what it needs ({@link
16
+ * RenameCascadeHost}) inside the queued step that makes the whole operation atomic with respect to
17
+ * every other write.
18
+ *
19
+ * @module
20
+ * @docs studio/projects/pages-layouts-components
21
+ */
22
+
23
+ import { extname } from "node:path";
24
+ import {
25
+ contentHash,
26
+ renameRollbackWriteId,
27
+ renameStepWriteId,
28
+ } from "@jxsuite/protocol/project-state";
29
+ import type {
30
+ BufferRewrite,
31
+ ContentHash,
32
+ RenameApplied,
33
+ RenameOperation,
34
+ RenameOperationResult,
35
+ RenameRefusalReason,
36
+ RenameRefused,
37
+ WriteRequest,
38
+ WriteResult,
39
+ } from "@jxsuite/protocol/project-state";
40
+ import type { AssetMount } from "@jxsuite/schema/asset-paths";
41
+ import type { FormatRegistry } from "@jxsuite/schema/format-registry";
42
+ import { errorMessage } from "@jxsuite/schema/parse";
43
+ import type { JsonValue } from "@jxsuite/schema/types";
44
+ import { planRename } from "../refactor/apply.ts";
45
+ import { parseDoc } from "../refactor/scan.ts";
46
+ import type { LoadedDoc } from "../refactor/scan.ts";
47
+
48
+ /** One file or directory the host's index holds. */
49
+ export interface RenameIndexEntry {
50
+ path: string;
51
+ isDir: boolean;
52
+ /** Whether the host extracted its references (§8.2). */
53
+ indexed: boolean;
54
+ }
55
+
56
+ /** The formats the host has loaded, `null` before `extensions-resolved` (§7). */
57
+ export interface RenameFormats {
58
+ /** Every file extension a registered format parses, lowercase with its dot. */
59
+ extensions: readonly string[];
60
+ parse: (extension: string, text: string) => Promise<JsonValue>;
61
+ /**
62
+ * The registry that also writes a registered format back; absent, such a document is named, not
63
+ * rewritten.
64
+ */
65
+ registry?: FormatRegistry;
66
+ mounts: readonly AssetMount[];
67
+ }
68
+
69
+ /** What the host lends the cascade for one operation, inside its queue. */
70
+ export interface RenameCascadeHost {
71
+ /** The absolute project root. */
72
+ root: string;
73
+ /** Every entry in the index, project-relative. */
74
+ entries: () => RenameIndexEntry[];
75
+ /**
76
+ * The documents whose references may name a file at `paths` (§8), or `null` when the graph cannot
77
+ * answer (it is not built, or its watcher is degraded) and every document is a candidate.
78
+ */
79
+ referrersOf: (paths: readonly string[]) => string[] | null;
80
+ formats: () => RenameFormats | null;
81
+ /** A file's bytes, `null` when nothing is there. */
82
+ read: (path: string) => Promise<Uint8Array | null>;
83
+ /**
84
+ * Whether `path` is taken on disk by something other than the operation's `from`: on a
85
+ * case-insensitive filesystem, `from` in another case is `from` itself, and a rename to it is a
86
+ * rename (`studio.md` §9.1.1).
87
+ */
88
+ exists: (path: string) => Promise<boolean>;
89
+ /**
90
+ * Move `from` to `to` through the index, as the write `writeId` (§9.1), answering the directories
91
+ * it created for `to`, outermost first. Throws on failure.
92
+ */
93
+ move: (from: string, to: string, writeId: string) => Promise<string[]>;
94
+ /**
95
+ * Remove each of `dirs` that is empty, innermost first, through the index, as the write
96
+ * `writeId`: the undo of the directories a move created.
97
+ */
98
+ removeDirs: (dirs: readonly string[], writeId: string) => Promise<void>;
99
+ /** A conditional write through the host, outside its queue (the caller holds it) (§5). */
100
+ write: (request: WriteRequest) => Promise<WriteResult>;
101
+ /** Append `operationApplied`, answering its revision (§4.7). */
102
+ applied: (opId: string, files: string[]) => number;
103
+ /** Called before each step runs, counted from 0; a throw fails that step. */
104
+ beforeStep?: (step: number, path: string) => void | Promise<void>;
105
+ }
106
+
107
+ /** Paths a rename never moves: their arrival and departure move the configuration and readiness. */
108
+ export type Unmovable = (path: string) => boolean;
109
+
110
+ /** A document extension the host reads without an extension: JSON and Jx Notation. */
111
+ const NATIVE_DOCUMENT = /\.(?:json|jxn)$/i;
112
+
113
+ /** Media and stylesheets: indexed by name, never parsed, never a referrer. */
114
+ const NOT_A_DOCUMENT =
115
+ /\.(?:css|png|jpe?g|gif|svg|webp|avif|ico|bmp|tiff?|mp4|webm|ogg|mov|mp3|wav|flac|m4a|woff2?|ttf|otf|eot|pdf)$/i;
116
+
117
+ /** Generated schema artifacts, which the refactor sweep never rewrites (`skipScanPath`). */
118
+ const GENERATED_SCHEMA = /\.schema\.json$/;
119
+
120
+ const decoder = new TextDecoder();
121
+
122
+ /** Whether `path` is `dir` or beneath it. */
123
+ const within = (path: string, dir: string): boolean => path === dir || path.startsWith(`${dir}/`);
124
+
125
+ /** Where `path` lands when `from` moves to `to`. */
126
+ const remap = (path: string, from: string, to: string): string =>
127
+ within(path, from) ? to + path.slice(from.length) : path;
128
+
129
+ /** The answer to a refused or failed operation (§9.1, §9.2). */
130
+ function refusal(
131
+ opId: string,
132
+ reason: RenameRefusalReason,
133
+ message: string,
134
+ paths: string[],
135
+ ): RenameRefused {
136
+ return { message, ok: false, opId, paths, reason };
137
+ }
138
+
139
+ /** One step of the outbox: what it does, and how to undo it once it has run. */
140
+ interface Step {
141
+ /** The path the step changes, after the move. */
142
+ path: string;
143
+ run: (writeId: string) => Promise<WriteResult | null>;
144
+ undo: (writeId: string) => Promise<void>;
145
+ }
146
+
147
+ /**
148
+ * Plan `operation`, refuse it or apply it (§9). Runs inside the host's queue, so nothing the host
149
+ * does interleaves; a program outside the host changing a referrer between planning and applying is
150
+ * caught by that step's base hash.
151
+ */
152
+ export async function runRenameCascade(
153
+ host: RenameCascadeHost,
154
+ operation: RenameOperation,
155
+ unmovable: Unmovable,
156
+ ): Promise<RenameOperationResult> {
157
+ const { from, opId, to } = operation;
158
+ if (from === to || within(to, from)) {
159
+ return refusal(opId, "failed", `"${from}" cannot be moved into itself.`, [to]);
160
+ }
161
+ if (unmovable(from) || unmovable(to)) {
162
+ return refusal(
163
+ opId,
164
+ "failed",
165
+ "The project configuration, the package manifest and the lockfiles are not renamed.",
166
+ [unmovable(from) ? from : to],
167
+ );
168
+ }
169
+ const entries = host.entries();
170
+ const top = entries.find((entry) => entry.path === from);
171
+ if (top === undefined) {
172
+ return refusal(opId, "conflict", `Nothing is at "${from}".`, [from]);
173
+ }
174
+ if (await host.exists(to)) {
175
+ return refusal(opId, "conflict", `"${to}" already exists.`, [to]);
176
+ }
177
+ const formats = host.formats();
178
+ const parses = (path: string): boolean => {
179
+ const extension = extname(path).toLowerCase();
180
+ return NATIVE_DOCUMENT.test(path) || (formats?.extensions.includes(extension) ?? false);
181
+ };
182
+ const isDocument = (entry: RenameIndexEntry): boolean =>
183
+ !entry.isDir && !GENERATED_SCHEMA.test(entry.path) && parses(entry.path);
184
+
185
+ /* ── Documents the host cannot parse (§8.2, §9.1) ──
186
+ Only before the formats are known: once they are, a file no format parses is no document, and
187
+ an unindexed one a format does parse (too large to index, say) is planned, read whole. */
188
+ const unplannable =
189
+ formats === null
190
+ ? entries
191
+ .filter(
192
+ (entry) =>
193
+ !entry.isDir &&
194
+ !entry.indexed &&
195
+ !parses(entry.path) &&
196
+ !NOT_A_DOCUMENT.test(entry.path),
197
+ )
198
+ .map((entry) => entry.path)
199
+ : [];
200
+ if (unplannable.length > 0 && operation.rewrites === undefined) {
201
+ return refusal(
202
+ opId,
203
+ "rewrites-required",
204
+ "Some documents cannot be read until the project's extensions load, so their references cannot be rewritten yet.",
205
+ unplannable,
206
+ );
207
+ }
208
+ const clientRewrites = new Map((operation.rewrites ?? []).map((item) => [item.path, item]));
209
+
210
+ // ── The candidates: what moves, what the graph says refers to it, the configuration ──
211
+ const moved = entries.filter((entry) => within(entry.path, from));
212
+ const movedFiles = moved.filter((entry) => !entry.isDir).map((entry) => entry.path);
213
+ const referrers = host.referrersOf(movedFiles);
214
+ const candidates = new Set<string>();
215
+ for (const entry of entries) {
216
+ const named =
217
+ referrers === null ||
218
+ within(entry.path, from) ||
219
+ !entry.indexed ||
220
+ referrers.includes(entry.path) ||
221
+ unmovable(entry.path);
222
+ if (named && isDocument(entry) && !clientRewrites.has(entry.path)) {
223
+ candidates.add(entry.path);
224
+ }
225
+ }
226
+
227
+ // ── The plan: every rewrite's bytes and the hash they replace, read before anything moves ──
228
+ const root = host.root.replaceAll("\\", "/");
229
+ const abs = (path: string): string => `${root}/${path}`;
230
+ const rel = (path: string): string => path.slice(root.length + 1);
231
+ const read = new Map<string, ContentHash>();
232
+ const load = async (fp: string): Promise<LoadedDoc> => {
233
+ const path = rel(fp);
234
+ const bytes = await host.read(path);
235
+ if (bytes === null) {
236
+ throw new Error(`"${path}" is gone`);
237
+ }
238
+ read.set(path, await contentHash(bytes));
239
+ const text = decoder.decode(bytes);
240
+ if (formats?.registry !== undefined || NATIVE_DOCUMENT.test(path)) {
241
+ return parseDoc(fp, text, formats?.registry ?? null);
242
+ }
243
+ // A registered format the host can read but not write: planned, then named in the report.
244
+ const doc = await formats!.parse(extname(path).toLowerCase(), text);
245
+ return { doc, rewrite: null, serialize: null };
246
+ };
247
+ let renamed: LoadedDoc | null = null;
248
+ if (!top.isDir && isDocument(top)) {
249
+ try {
250
+ renamed = await load(abs(from));
251
+ } catch {
252
+ // Not a parseable document: no tag to derive.
253
+ }
254
+ }
255
+ const plan = await planRename({
256
+ absFrom: abs(from),
257
+ absTo: abs(to),
258
+ documents: [...candidates].toSorted().map((path) => abs(path)),
259
+ load,
260
+ mounts: formats?.mounts ?? [],
261
+ phase: "before",
262
+ renamed,
263
+ root,
264
+ });
265
+
266
+ // ── Dirty referrers (§9.2) ──
267
+ const dirty = new Map(operation.dirtyReferrers.map((item) => [item.path, item.bufferRev]));
268
+ // Every path in the answer names the file after the move.
269
+ const errors = plan.errors.map((entry) => ({
270
+ error: entry.error,
271
+ path: remap(rel(entry.abs), from, to),
272
+ }));
273
+ const buffers: BufferRewrite[] = [];
274
+ const refused: string[] = [];
275
+ const writes: {
276
+ path: string;
277
+ base: ContentHash;
278
+ contents: string | Uint8Array;
279
+ refs: number;
280
+ tags: number;
281
+ /** A client's rewrite (§9.1), whose references the host did not count. */
282
+ client: boolean;
283
+ }[] = [];
284
+ for (const planned of plan.rewrites) {
285
+ const path = rel(planned.abs);
286
+ const bufferRev = dirty.get(path);
287
+ if (bufferRev !== undefined) {
288
+ if (operation.policy === "refuse") {
289
+ refused.push(path);
290
+ continue;
291
+ }
292
+ const rewrite: BufferRewrite = {
293
+ bufferRev,
294
+ changes: planned.changes.map((change) => ({ from: change.from, to: change.to })),
295
+ path,
296
+ };
297
+ if (planned.tagCount > 0 && plan.tagRename !== null) {
298
+ rewrite.tag = { ...plan.tagRename };
299
+ }
300
+ buffers.push(rewrite);
301
+ continue;
302
+ }
303
+ if (planned.contents === null) {
304
+ errors.push({
305
+ error: `No serializer for "${remap(path, from, to)}"`,
306
+ path: remap(path, from, to),
307
+ });
308
+ continue;
309
+ }
310
+ writes.push({
311
+ base: read.get(path)!,
312
+ contents: planned.contents,
313
+ client: false,
314
+ path: remap(path, from, to),
315
+ refs: planned.changes.length,
316
+ tags: planned.tagCount,
317
+ });
318
+ }
319
+ for (const rewrite of clientRewrites.values()) {
320
+ const bufferRev = dirty.get(rewrite.path);
321
+ if (bufferRev !== undefined) {
322
+ if (operation.policy === "refuse") {
323
+ refused.push(rewrite.path);
324
+ continue;
325
+ }
326
+ // The client computed this rewrite, so it applies it to its buffer; the file stays (§9.2).
327
+ buffers.push({ bufferRev, changes: [], path: rewrite.path });
328
+ continue;
329
+ }
330
+ writes.push({
331
+ base: rewrite.baseHash,
332
+ client: true,
333
+ contents: rewrite.contents,
334
+ path: remap(rewrite.path, from, to),
335
+ refs: 0,
336
+ tags: 0,
337
+ });
338
+ }
339
+ if (refused.length > 0) {
340
+ return refusal(
341
+ opId,
342
+ "dirty-referrers",
343
+ "Some documents that refer to it have unsaved edits.",
344
+ refused,
345
+ );
346
+ }
347
+
348
+ // ── The outbox: the move, then every rewrite at its path after the move ──
349
+ /** The bytes each rewritten file held when its step ran, for its undo. */
350
+ const original = new Map<string, Uint8Array>();
351
+ /** The directories the move created for `to`, which its undo removes again. */
352
+ let created: string[] = [];
353
+ const steps: Step[] = [
354
+ {
355
+ path: to,
356
+ run: async (writeId) => {
357
+ created = await host.move(from, to, writeId);
358
+ return null;
359
+ },
360
+ undo: async (writeId) => {
361
+ await host.move(to, from, writeId);
362
+ await host.removeDirs(created, writeId);
363
+ },
364
+ },
365
+ ...writes.map((write): Step => ({
366
+ path: write.path,
367
+ run: (writeId) =>
368
+ host.write({
369
+ baseHash: write.base,
370
+ contents: write.contents,
371
+ path: write.path,
372
+ writeId,
373
+ }),
374
+ undo: async (writeId) => {
375
+ // Back to the bytes the step replaced, against the bytes it wrote.
376
+ const restored = await host.write({
377
+ baseHash: await contentHash(write.contents),
378
+ contents: original.get(write.path)!,
379
+ path: write.path,
380
+ writeId,
381
+ });
382
+ if (!restored.ok) {
383
+ throw new Error(`"${write.path}" changed again before it could be restored`);
384
+ }
385
+ },
386
+ })),
387
+ ];
388
+ const completed: number[] = [];
389
+ const rollback = async (): Promise<{ path: string; error: string }[]> => {
390
+ const failures: { path: string; error: string }[] = [];
391
+ for (const at of completed.toReversed()) {
392
+ try {
393
+ await steps[at]!.undo(renameRollbackWriteId(opId, at));
394
+ } catch (error) {
395
+ failures.push({ error: errorMessage(error), path: steps[at]!.path });
396
+ }
397
+ }
398
+ return failures;
399
+ };
400
+ const failed = async (
401
+ reason: RenameRefusalReason,
402
+ message: string,
403
+ paths: string[],
404
+ ): Promise<RenameOperationResult> => {
405
+ const failures = await rollback();
406
+ if (failures.length === 0) {
407
+ return refusal(opId, reason, `${message} Nothing was changed.`, paths);
408
+ }
409
+ const listed = failures.map((failure) => `${failure.path}: ${failure.error}`).join("; ");
410
+ return {
411
+ ...refusal(opId, reason, `${message} Some steps could not be undone: ${listed}.`, paths),
412
+ unrestored: failures.map((failure) => failure.path),
413
+ };
414
+ };
415
+ for (const [at, step] of steps.entries()) {
416
+ let result: WriteResult | null;
417
+ try {
418
+ await host.beforeStep?.(at, step.path);
419
+ if (at > 0) {
420
+ const before = await host.read(step.path);
421
+ if (before !== null) {
422
+ original.set(step.path, before);
423
+ }
424
+ }
425
+ result = await step.run(renameStepWriteId(opId, at));
426
+ } catch (error) {
427
+ return failed("failed", `The rename failed at "${step.path}": ${errorMessage(error)}.`, [
428
+ step.path,
429
+ ]);
430
+ }
431
+ if (result !== null && !result.ok) {
432
+ return failed("conflict", `"${step.path}" changed while the rename was being applied.`, [
433
+ step.path,
434
+ ]);
435
+ }
436
+ completed.push(at);
437
+ }
438
+
439
+ // ── Done: one operationApplied after every step's events (§4.7) ──
440
+ // The moved document can also be a rewrite step (its own tag): name each path once, the move first.
441
+ const files = [...new Set(steps.map((step) => step.path))];
442
+ const rev = host.applied(opId, files);
443
+ // A client's rewrite counts its file: the host did not count its references.
444
+ const referenced = writes.filter((write) => write.refs > 0 || write.client);
445
+ const applied: RenameApplied = {
446
+ buffers,
447
+ errors,
448
+ files,
449
+ from,
450
+ isDir: top.isDir,
451
+ ok: true,
452
+ opId,
453
+ references: {
454
+ files: referenced.map((write) => ({ count: write.refs, path: write.path })),
455
+ filesChanged: referenced.length,
456
+ refsUpdated: referenced.reduce((sum, write) => sum + write.refs, 0),
457
+ },
458
+ rev,
459
+ to,
460
+ };
461
+ if (plan.tagRename !== null) {
462
+ const tagged = writes.filter((write) => write.tags > 0);
463
+ applied.tag = {
464
+ ...plan.tagRename,
465
+ filesChanged: tagged.length,
466
+ refsUpdated: tagged.reduce((sum, write) => sum + write.tags, 0),
467
+ };
468
+ }
469
+ if (plan.tagSkipped !== undefined) {
470
+ applied.tagSkipped = plan.tagSkipped;
471
+ }
472
+ return applied;
473
+ }