@catamorphic/git 0.0.0-stage → 0.1.0-alpha.30

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.
Files changed (79) hide show
  1. package/LICENSE.txt +202 -0
  2. package/NOTICE.txt +32 -0
  3. package/dist/checkout-remote-backend.d.ts +12 -0
  4. package/dist/checkout-remote-backend.d.ts.map +1 -0
  5. package/dist/file-reads.d.ts +15 -0
  6. package/dist/file-reads.d.ts.map +1 -0
  7. package/dist/fs-backend.d.ts +30 -0
  8. package/dist/fs-backend.d.ts.map +1 -0
  9. package/dist/fs-remote-backend.d.ts +47 -0
  10. package/dist/fs-remote-backend.d.ts.map +1 -0
  11. package/dist/git-object-codec.d.ts +31 -0
  12. package/dist/git-object-codec.d.ts.map +1 -0
  13. package/dist/git-sync.d.ts +61 -0
  14. package/dist/git-sync.d.ts.map +1 -0
  15. package/dist/in-memory-object-store.d.ts +23 -0
  16. package/dist/in-memory-object-store.d.ts.map +1 -0
  17. package/dist/index.d.ts +24 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +4746 -0
  20. package/dist/index.js.map +32 -0
  21. package/dist/migrate-workflow.d.ts +12 -0
  22. package/dist/migrate-workflow.d.ts.map +1 -0
  23. package/dist/native-git.d.ts +25 -0
  24. package/dist/native-git.d.ts.map +1 -0
  25. package/dist/native-project-repo.d.ts +57 -0
  26. package/dist/native-project-repo.d.ts.map +1 -0
  27. package/dist/network-sync.d.ts +58 -0
  28. package/dist/network-sync.d.ts.map +1 -0
  29. package/dist/network.d.ts +81 -0
  30. package/dist/network.d.ts.map +1 -0
  31. package/dist/object-remote-backend.d.ts +95 -0
  32. package/dist/object-remote-backend.d.ts.map +1 -0
  33. package/dist/object-store.d.ts +42 -0
  34. package/dist/object-store.d.ts.map +1 -0
  35. package/dist/origin-draft.d.ts +264 -0
  36. package/dist/origin-draft.d.ts.map +1 -0
  37. package/dist/origin-objects.d.ts +201 -0
  38. package/dist/origin-objects.d.ts.map +1 -0
  39. package/dist/personal-files.d.ts +6 -0
  40. package/dist/personal-files.d.ts.map +1 -0
  41. package/dist/project-manager.d.ts +214 -0
  42. package/dist/project-manager.d.ts.map +1 -0
  43. package/dist/project-repo.d.ts +79 -0
  44. package/dist/project-repo.d.ts.map +1 -0
  45. package/dist/ref-moved-error.d.ts +13 -0
  46. package/dist/ref-moved-error.d.ts.map +1 -0
  47. package/dist/ref-names.d.ts +18 -0
  48. package/dist/ref-names.d.ts.map +1 -0
  49. package/dist/types.d.ts +276 -0
  50. package/dist/types.d.ts.map +1 -0
  51. package/dist/workspace-mirror.d.ts +110 -0
  52. package/dist/workspace-mirror.d.ts.map +1 -0
  53. package/package.json +53 -4
  54. package/src/checkout-remote-backend.ts +154 -0
  55. package/src/diff3.d.ts +16 -0
  56. package/src/file-reads.ts +53 -0
  57. package/src/fs-backend.ts +206 -0
  58. package/src/fs-remote-backend.ts +252 -0
  59. package/src/git-object-codec.ts +87 -0
  60. package/src/git-sync.ts +539 -0
  61. package/src/in-memory-object-store.ts +60 -0
  62. package/src/index.ts +110 -0
  63. package/src/migrate-workflow.ts +30 -0
  64. package/src/native-git.ts +177 -0
  65. package/src/native-project-repo.ts +515 -0
  66. package/src/network-sync.ts +239 -0
  67. package/src/network.ts +269 -0
  68. package/src/object-remote-backend.ts +366 -0
  69. package/src/object-store.ts +41 -0
  70. package/src/origin-draft.ts +1033 -0
  71. package/src/origin-objects.ts +906 -0
  72. package/src/personal-files.ts +57 -0
  73. package/src/project-manager.ts +743 -0
  74. package/src/project-repo.ts +800 -0
  75. package/src/ref-moved-error.ts +18 -0
  76. package/src/ref-names.ts +47 -0
  77. package/src/types.ts +289 -0
  78. package/src/workspace-mirror.ts +400 -0
  79. package/README.md +0 -3
@@ -0,0 +1,1033 @@
1
+ import path from "node:path";
2
+ import {
3
+ DRAFT_REF_PREFIX,
4
+ draftRef,
5
+ PUBLISHED_REF_PREFIX,
6
+ publishedRef,
7
+ SYSTEM_COMMIT_AUTHOR,
8
+ } from "@catamorphic/workflow/project-layout";
9
+ import { type FileReadOptions, readFileSnapshot } from "./file-reads.js";
10
+ import { fetchRemote } from "./git-sync.js";
11
+ import {
12
+ DraftIgnoredPathError,
13
+ DraftPathError,
14
+ type GitObjectCache,
15
+ type IgnoreRules,
16
+ isTreeMode,
17
+ mergeTrees,
18
+ OriginObjects,
19
+ SYMLINK_MODE,
20
+ type TreeChange,
21
+ } from "./origin-objects.js";
22
+ import { assertSafePath } from "./project-repo.js";
23
+ import { RefMovedError } from "./ref-moved-error.js";
24
+ import { assertValidRefName } from "./ref-names.js";
25
+ import type {
26
+ CommitInfo,
27
+ ConflictEntry,
28
+ DiffEntry,
29
+ MergeResult,
30
+ ProjectRepo,
31
+ RemoteBackend,
32
+ RepoStatus,
33
+ } from "./types.js";
34
+
35
+ const MAIN = "refs/heads/main";
36
+ const BRANCHES = "refs/heads/";
37
+ /** Branches that hold one session's work, private to it. */
38
+ const SESSION_BRANCHES = `${BRANCHES}sessions/`;
39
+ const SHA_RE = /^[0-9a-f]{40}$/;
40
+ /** Lost compare-and-swap races before a write gives up. */
41
+ const MAX_ATTEMPTS = 8;
42
+
43
+ /**
44
+ * A member's draft as {@link ProjectManager.openDraft} returns it: a local
45
+ * folder's checkout, or a draft ref in a server-hosted project's origin.
46
+ */
47
+ export type ProjectDraft = ProjectRepo | OriginDraftRepo;
48
+
49
+ /** One change to a draft: new content, or `delete: true`. */
50
+ export type DraftChange =
51
+ | { path: string; content: string | Uint8Array }
52
+ | { path: string; delete: true };
53
+
54
+ export type DraftPublishResult =
55
+ | {
56
+ status: "deployed";
57
+ commitSha: string;
58
+ remoteSha: string;
59
+ conflicts: ConflictEntry[];
60
+ }
61
+ | {
62
+ status: "nothing-to-deploy";
63
+ commitSha: null;
64
+ remoteSha: string | null;
65
+ conflicts: ConflictEntry[];
66
+ }
67
+ | {
68
+ status: "conflict";
69
+ commitSha: string;
70
+ remoteSha: string;
71
+ conflicts: ConflictEntry[];
72
+ };
73
+
74
+ /** Every attempt to move a ref lost its race to another writer. */
75
+ export class DraftBusyError extends Error {
76
+ constructor() {
77
+ super("The project changed while saving. Try again.");
78
+ this.name = "DraftBusyError";
79
+ }
80
+ }
81
+
82
+ /** A file no longer holds the content a write expected. */
83
+ export class DraftContentChangedError extends Error {
84
+ constructor(path: string) {
85
+ super(`${path} changed since it was read`);
86
+ this.name = "DraftContentChangedError";
87
+ }
88
+ }
89
+
90
+ /** A ref that a member's draft may not read (another member's draft). */
91
+ export class DraftRefNotAllowedError extends Error {
92
+ constructor(ref: string) {
93
+ super(`Unknown ref: ${ref}`);
94
+ this.name = "DraftRefNotAllowedError";
95
+ }
96
+ }
97
+
98
+ /** A `base` that is not a commit of the published program. */
99
+ export class InvalidBaseError extends Error {
100
+ constructor(base: string) {
101
+ super(`${base} is not a commit of the published program`);
102
+ this.name = "InvalidBaseError";
103
+ }
104
+ }
105
+
106
+ /** A read-only view (no member) asked to change a draft. */
107
+ export class NoDraftError extends Error {
108
+ constructor() {
109
+ super("This view of the program has no draft to change");
110
+ this.name = "NoDraftError";
111
+ }
112
+ }
113
+
114
+ /** The conflicts a merge left without a resolution. */
115
+ export class DraftUnresolvedError extends Error {
116
+ readonly conflicts: ConflictEntry[];
117
+ constructor(conflicts: ConflictEntry[]) {
118
+ super(
119
+ `Resolve ${conflicts.map((conflict) => conflict.path).join(", ")} too.`,
120
+ );
121
+ this.name = "DraftUnresolvedError";
122
+ this.conflicts = conflicts;
123
+ }
124
+ }
125
+
126
+ /** An origin that cannot keep drafts safely (ADR 0191). */
127
+ export class DraftsUnsupportedError extends Error {
128
+ constructor(reason: string) {
129
+ super(`Member drafts are unavailable on this project storage: ${reason}`);
130
+ this.name = "DraftsUnsupportedError";
131
+ }
132
+ }
133
+
134
+ type PublishPlan =
135
+ | { kind: "done"; done: DraftPublishResult }
136
+ | { kind: "publish"; draft: string; main: string | null; tree: string };
137
+
138
+ type MergePlan =
139
+ | { kind: "done"; result: MergeResult }
140
+ | { kind: "merged"; draft: string; main: string; tree: string };
141
+
142
+ /**
143
+ * A member's draft of a server-hosted project's program (ADR 0191): the ref
144
+ * `refs/work/drafts/<member>` in the project's origin, read and written as
145
+ * objects with no working copy on any machine. Without that ref the draft
146
+ * is the published `main`. Every write is a draft commit moved in with a
147
+ * compare-and-swap, so any replica sees every earlier write and nothing is
148
+ * lost when one restarts. Publishing squashes the draft into one commit on
149
+ * `main`, merging in memory with a `main` that moved since the draft began.
150
+ *
151
+ * Reads of `HEAD` within one open see one commit (the one the first read
152
+ * found, or the latest write through this instance), so several files read
153
+ * together always come from the same snapshot. Reads accept `HEAD`, `main`
154
+ * and published refs, other published branches, and commit ids reachable
155
+ * from those or from the member's own draft; never another member's draft
156
+ * or a session branch, by any spelling or case.
157
+ *
158
+ * Without a member (`externalUserId: null`) it is a read-only view of the
159
+ * published program.
160
+ */
161
+ export class OriginDraftRepo {
162
+ readonly projectId: string;
163
+ /** The draft's ref in the origin, or null for a read-only view. */
164
+ readonly ref: string | null;
165
+ private readonly tenantId: string;
166
+ private readonly remote: RemoteBackend;
167
+ private readonly cache: GitObjectCache;
168
+ private readonly author: { name: string; email: string };
169
+ /** The commit `HEAD` reads see; resolved on first use. */
170
+ private head: { sha: string | null } | undefined;
171
+ /** Commit ids this instance proved readable. */
172
+ private readonly readable = new Set<string>();
173
+
174
+ constructor(args: {
175
+ tenantId: string;
176
+ projectId: string;
177
+ externalUserId: string | null;
178
+ remote: RemoteBackend;
179
+ cache: GitObjectCache;
180
+ /** Author of draft commits; publishing records the publisher. */
181
+ author?: { name: string; email: string };
182
+ }) {
183
+ this.tenantId = args.tenantId;
184
+ this.projectId = args.projectId;
185
+ this.ref =
186
+ args.externalUserId === null ? null : draftRef(args.externalUserId);
187
+ this.remote = args.remote;
188
+ this.cache = args.cache;
189
+ this.author = args.author ?? SYSTEM_COMMIT_AUTHOR;
190
+ }
191
+
192
+ private withObjects<T>(fn: (objects: OriginObjects) => Promise<T>) {
193
+ return this.remote.withOrigin(this.tenantId, this.projectId, (origin) =>
194
+ fn(new OriginObjects(origin, this.cache)),
195
+ );
196
+ }
197
+
198
+ /**
199
+ * Run one compare-and-swap attempt; a lost race (inside the attempt, or
200
+ * reported by the origin when it publishes the ref) yields null.
201
+ */
202
+ private async attempt<T>(
203
+ fn: (objects: OriginObjects) => Promise<T | null>,
204
+ ): Promise<T | null> {
205
+ try {
206
+ return await this.withObjects(async (objects) => {
207
+ try {
208
+ return await fn(objects);
209
+ } catch (error) {
210
+ if (error instanceof RefMovedError) return null;
211
+ throw error;
212
+ }
213
+ });
214
+ } catch (error) {
215
+ if (error instanceof RefMovedError) return null;
216
+ throw error;
217
+ }
218
+ }
219
+
220
+ private async tips(
221
+ objects: OriginObjects,
222
+ ): Promise<{ draft: string | null; main: string | null }> {
223
+ const [draft, main] = await Promise.all([
224
+ this.ref ? objects.origin.resolveRef(this.ref) : null,
225
+ objects.origin.resolveRef(MAIN),
226
+ ]);
227
+ return { draft, main };
228
+ }
229
+
230
+ /** This member's draft ref; a read-only view has none to change. */
231
+ private draftRefOrThrow(): string {
232
+ if (!this.ref) throw new NoDraftError();
233
+ return this.ref;
234
+ }
235
+
236
+ /**
237
+ * Whether a commit id may be read here: reachable from `main`, from this
238
+ * member's draft, or from a published branch this member may name. Ids
239
+ * of other members' drafts or of sessions are not capabilities.
240
+ */
241
+ private async mayReadCommit(
242
+ objects: OriginObjects,
243
+ sha: string,
244
+ ): Promise<boolean> {
245
+ if (this.readable.has(sha)) return true;
246
+ const { draft, main } = await this.tips(objects);
247
+ const own = [draft, main].filter((tip): tip is string => tip !== null);
248
+ let reachable = await objects.isReachable({ sha, tips: own });
249
+ if (!reachable) {
250
+ const branches = (await objects.origin.listRefs(BRANCHES))
251
+ .filter((entry) => !isPrivateRef(entry.ref) && entry.ref !== MAIN)
252
+ .map((entry) => entry.sha);
253
+ reachable =
254
+ branches.length > 0 &&
255
+ (await objects.isReachable({ sha, tips: branches }));
256
+ }
257
+ if (reachable) this.readable.add(sha);
258
+ return reachable;
259
+ }
260
+
261
+ /**
262
+ * The commit a ref names, as this member may read it. Every name is
263
+ * checked against git's ref rules first, then the full ref it maps to
264
+ * against the private namespaces, so no spelling reaches another
265
+ * member's draft or a session's branch.
266
+ */
267
+ private async resolveIn(
268
+ objects: OriginObjects,
269
+ ref: string,
270
+ ): Promise<string | null> {
271
+ if (ref === "HEAD" || ref === this.ref) {
272
+ if (!this.head) {
273
+ const { draft, main } = await this.tips(objects);
274
+ this.head = { sha: draft ?? main };
275
+ }
276
+ return this.head.sha;
277
+ }
278
+ if (SHA_RE.test(ref))
279
+ return (await this.mayReadCommit(objects, ref)) ? ref : null;
280
+ assertValidRefName(ref);
281
+ const full = ref.startsWith(`${PUBLISHED_REF_PREFIX}/`)
282
+ ? `${BRANCHES}${ref.slice(PUBLISHED_REF_PREFIX.length + 1)}`
283
+ : ref.startsWith("refs/")
284
+ ? ref
285
+ : `${BRANCHES}${ref}`;
286
+ assertValidRefName(full);
287
+ if (!full.startsWith(BRANCHES) || isPrivateRef(full))
288
+ throw new DraftRefNotAllowedError(ref);
289
+ return objects.origin.resolveRef(full);
290
+ }
291
+
292
+ private async treeAt(objects: OriginObjects, ref: string): Promise<string> {
293
+ const sha = await this.resolveIn(objects, ref);
294
+ if (!sha) throw new Error(`Unknown ref: ${ref}`);
295
+ return (await objects.commit(sha)).tree;
296
+ }
297
+
298
+ async resolveRef(ref = "HEAD"): Promise<string> {
299
+ const sha = await this.withObjects((objects) =>
300
+ this.resolveIn(objects, ref),
301
+ );
302
+ if (!sha) throw new Error(`Unknown ref: ${ref}`);
303
+ return sha;
304
+ }
305
+
306
+ async readFileBytes(filePath: string): Promise<Uint8Array | null> {
307
+ const normalized = normalizePath(filePath);
308
+ return this.withObjects(async (objects) => {
309
+ const head = await this.resolveIn(objects, "HEAD");
310
+ if (!head) return null;
311
+ const entry = await objects.entry(
312
+ (await objects.commit(head)).tree,
313
+ normalized,
314
+ );
315
+ if (!entry || isTreeMode(entry.mode)) return null;
316
+ if (entry.mode === SYMLINK_MODE)
317
+ throw new DraftPathError({ code: "ELOOP", path: normalized });
318
+ return objects.blob(entry.oid);
319
+ });
320
+ }
321
+
322
+ async readFile(filePath: string): Promise<string> {
323
+ const bytes = await this.readFileBytes(filePath);
324
+ if (!bytes)
325
+ throw new DraftPathError({
326
+ code: "ENOENT",
327
+ path: normalizePath(filePath),
328
+ });
329
+ return new TextDecoder().decode(bytes);
330
+ }
331
+
332
+ async listFiles(opts?: { prefix?: string }): Promise<string[]> {
333
+ const prefix = opts?.prefix
334
+ ? `${normalizePath(opts.prefix).replace(/\/+$/, "")}/`
335
+ : undefined;
336
+ return this.listFilesAtRef("HEAD", prefix ? { prefix } : undefined);
337
+ }
338
+
339
+ async readAllFiles(
340
+ options?: FileReadOptions,
341
+ ): Promise<Record<string, string>> {
342
+ return this.readAllFilesAtRef("HEAD", options);
343
+ }
344
+
345
+ async listBlobsAtRef(
346
+ ref: string,
347
+ opts?: { prefix?: string },
348
+ ): Promise<Array<{ path: string; oid: string }>> {
349
+ return this.withObjects(async (objects) => {
350
+ const sha = await this.resolveIn(objects, ref);
351
+ if (!sha) return [];
352
+ const files = await objects.files(
353
+ (await objects.commit(sha)).tree,
354
+ opts?.prefix,
355
+ );
356
+ return [...files]
357
+ .map(([filePath, file]) => ({ path: filePath, oid: file.oid }))
358
+ .sort((a, b) => a.path.localeCompare(b.path));
359
+ });
360
+ }
361
+
362
+ async listFilesAtRef(
363
+ ref: string,
364
+ opts?: { prefix?: string },
365
+ ): Promise<string[]> {
366
+ return (await this.listBlobsAtRef(ref, opts)).map((entry) => entry.path);
367
+ }
368
+
369
+ async readBlobAtRef(
370
+ ref: string,
371
+ filePath: string,
372
+ options?: { maxBytes?: number },
373
+ ): Promise<Uint8Array | null> {
374
+ const normalized = normalizePath(filePath);
375
+ const blob = await this.withObjects(async (objects) => {
376
+ const sha = await this.resolveIn(objects, ref);
377
+ if (!sha) return null;
378
+ const entry = await objects
379
+ .entry((await objects.commit(sha)).tree, normalized)
380
+ .catch(() => null);
381
+ if (!entry || isTreeMode(entry.mode)) return null;
382
+ return objects.blob(entry.oid);
383
+ });
384
+ if (
385
+ blob &&
386
+ options?.maxBytes !== undefined &&
387
+ blob.byteLength > options.maxBytes
388
+ )
389
+ throw new Error(
390
+ `Project file '${normalized}' exceeds the ${options.maxBytes}-byte snapshot limit`,
391
+ );
392
+ return blob;
393
+ }
394
+
395
+ async readAllFilesAtRef(
396
+ ref: string,
397
+ options?: FileReadOptions,
398
+ ): Promise<Record<string, string>> {
399
+ return this.snapshotAt(ref, undefined, options);
400
+ }
401
+
402
+ async readFilesAtRef(
403
+ ref: string,
404
+ opts: { prefix: string },
405
+ ): Promise<Record<string, string>> {
406
+ return this.snapshotAt(ref, opts.prefix);
407
+ }
408
+
409
+ private async snapshotAt(
410
+ ref: string,
411
+ prefix: string | undefined,
412
+ options?: FileReadOptions,
413
+ ): Promise<Record<string, string>> {
414
+ return this.withObjects(async (objects) => {
415
+ const sha = await this.resolveIn(objects, ref);
416
+ if (!sha) return {};
417
+ const files = await objects.files(
418
+ (await objects.commit(sha)).tree,
419
+ prefix,
420
+ );
421
+ return readFileSnapshot({
422
+ paths: [...files.keys()].sort(),
423
+ options,
424
+ read: async (file, maxBytes) => {
425
+ const entry = files.get(file);
426
+ if (!entry) return null;
427
+ const blob = await objects.blob(entry.oid);
428
+ if (blob.byteLength > maxBytes)
429
+ throw new Error(
430
+ `Project file '${file}' exceeds the ${maxBytes}-byte snapshot limit`,
431
+ );
432
+ return new TextDecoder().decode(blob);
433
+ },
434
+ });
435
+ });
436
+ }
437
+
438
+ async writeFile(
439
+ filePath: string,
440
+ content: string,
441
+ opts?: { message?: string },
442
+ ): Promise<void> {
443
+ await this.write({
444
+ changes: [{ path: filePath, content }],
445
+ message: opts?.message,
446
+ });
447
+ }
448
+
449
+ async deleteFile(
450
+ filePath: string,
451
+ opts?: { message?: string },
452
+ ): Promise<void> {
453
+ await this.write({
454
+ changes: [{ path: filePath, delete: true }],
455
+ message: opts?.message,
456
+ });
457
+ }
458
+
459
+ /**
460
+ * Apply changes as one draft commit, starting the draft from `main` when
461
+ * the member has none. File contents are written to the origin once; a
462
+ * write that loses the race to another writer of the same draft rebuilds
463
+ * only its trees on the winner and retries. Returns the draft's tip,
464
+ * unchanged when the changes change nothing.
465
+ *
466
+ * Paths the project's ignore rules keep out of history are refused, or
467
+ * dropped with `skipIgnored`; with `skipMissingDeletes`, deleting a file
468
+ * the draft lacks is not an error (a sandbox sync reporting a file it
469
+ * made and removed again).
470
+ */
471
+ async write(input: {
472
+ changes: readonly DraftChange[];
473
+ message?: string;
474
+ /**
475
+ * The content each path must still have, checked against the commit
476
+ * the write builds on; a mismatch throws {@link DraftContentChangedError}.
477
+ */
478
+ expected?: Record<string, string>;
479
+ skipIgnored?: boolean;
480
+ skipMissingDeletes?: boolean;
481
+ }): Promise<string | null> {
482
+ const pending = new Map<string, Uint8Array | null>();
483
+ for (const change of input.changes)
484
+ pending.set(
485
+ normalizePath(change.path),
486
+ "delete" in change
487
+ ? null
488
+ : typeof change.content === "string"
489
+ ? new TextEncoder().encode(change.content)
490
+ : change.content,
491
+ );
492
+ const draftRefName = this.draftRefOrThrow();
493
+ if (pending.size === 0) return null;
494
+ const message =
495
+ input.message ??
496
+ `Draft: ${[...pending.keys()].slice(0, 3).join(", ")}${pending.size > 3 ? ", ..." : ""}`;
497
+ // Contents are immutable objects: write them once, before any race.
498
+ const written = [...pending].filter(
499
+ (entry): entry is [string, Uint8Array] => entry[1] !== null,
500
+ );
501
+ const oids = await this.withObjects((objects) =>
502
+ objects.writeBlobs(written.map(([, content]) => content)),
503
+ );
504
+ const blobs = new Map(written.map(([file], index) => [file, oids[index]]));
505
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
506
+ const outcome = await this.attempt(async (objects) => {
507
+ const { draft, main } = await this.tips(objects);
508
+ const parent = draft ?? main;
509
+ const baseTree = parent ? (await objects.commit(parent)).tree : null;
510
+ for (const [file, content] of Object.entries(input.expected ?? {})) {
511
+ const entry = baseTree
512
+ ? await objects.entry(baseTree, normalizePath(file))
513
+ : null;
514
+ const current =
515
+ entry && !isTreeMode(entry.mode)
516
+ ? new TextDecoder().decode(await objects.blob(entry.oid))
517
+ : null;
518
+ if (current !== content) throw new DraftContentChangedError(file);
519
+ }
520
+ const rules: IgnoreRules = new Map();
521
+ const ignored: string[] = [];
522
+ const changes = new Map<string, TreeChange>();
523
+ for (const [file] of pending) {
524
+ if (await objects.isIgnored(baseTree, file, rules)) {
525
+ ignored.push(file);
526
+ continue;
527
+ }
528
+ const oid = blobs.get(file);
529
+ changes.set(file, oid ? { oid } : null);
530
+ }
531
+ if (ignored.length > 0 && !input.skipIgnored)
532
+ throw new DraftIgnoredPathError(ignored);
533
+ if (changes.size === 0) return { sha: parent };
534
+ const tree = await objects.writeTree(baseTree, changes, {
535
+ skipMissingDeletes: input.skipMissingDeletes,
536
+ });
537
+ if (tree === baseTree) return { sha: parent };
538
+ const sha = await objects.writeCommit({
539
+ tree,
540
+ parents: parent ? [parent] : [],
541
+ author: this.author,
542
+ message,
543
+ });
544
+ await objects.origin.updateRef({
545
+ ref: draftRefName,
546
+ sha,
547
+ expected: draft,
548
+ });
549
+ return { sha };
550
+ });
551
+ if (outcome) {
552
+ this.head = { sha: outcome.sha };
553
+ return outcome.sha;
554
+ }
555
+ }
556
+ throw new DraftBusyError();
557
+ }
558
+
559
+ async log(options?: {
560
+ maxCount?: number;
561
+ ref?: string;
562
+ }): Promise<CommitInfo[]> {
563
+ return this.withObjects(async (objects) => {
564
+ const tip = await this.resolveIn(objects, options?.ref ?? "HEAD");
565
+ return tip ? objects.log(tip, options?.maxCount ?? 50) : [];
566
+ });
567
+ }
568
+
569
+ /**
570
+ * What the draft would publish: the files it changes since it last met
571
+ * `main`, its commits, and how far `main` has moved since. A draft with
572
+ * no changes is clean.
573
+ */
574
+ async status(): Promise<RepoStatus> {
575
+ return this.withObjects(async (objects) => {
576
+ const { draft, main } = await this.tips(objects);
577
+ const clean = {
578
+ branch: "main",
579
+ dirty: false,
580
+ modifiedFiles: [],
581
+ ahead: 0,
582
+ behind: 0,
583
+ baseCommit: main,
584
+ remoteHead: main,
585
+ };
586
+ if (!draft) return clean;
587
+ const { base, ahead, behind } = main
588
+ ? await objects.compare(draft, main)
589
+ : { base: null, ahead: 0, behind: 0 };
590
+ const changes = await objects.diffTrees(
591
+ base ? (await objects.commit(base)).tree : null,
592
+ (await objects.commit(draft)).tree,
593
+ );
594
+ return {
595
+ ...clean,
596
+ dirty: changes.length > 0,
597
+ modifiedFiles: changes.map((change) => change.path),
598
+ ahead,
599
+ behind,
600
+ baseCommit: draft,
601
+ };
602
+ });
603
+ }
604
+
605
+ /** The draft's changes since it last met `main`, with contents. */
606
+ async workdirDiff(): Promise<DiffEntry[]> {
607
+ return this.withObjects(async (objects) => {
608
+ const { draft, main } = await this.tips(objects);
609
+ if (!draft) return [];
610
+ const base = main ? (await objects.compare(draft, main)).base : null;
611
+ return describeChanges({
612
+ objects,
613
+ before: base ? (await objects.commit(base)).tree : null,
614
+ after: (await objects.commit(draft)).tree,
615
+ });
616
+ });
617
+ }
618
+
619
+ async diff(opts: { base: string; head: string }): Promise<DiffEntry[]> {
620
+ return this.withObjects(async (objects) =>
621
+ describeChanges({
622
+ objects,
623
+ before: await this.treeAt(objects, opts.base),
624
+ after: await this.treeAt(objects, opts.head),
625
+ }),
626
+ );
627
+ }
628
+
629
+ /** Delete the draft: the member's view follows `main` again. */
630
+ async discard(): Promise<boolean> {
631
+ const ref = this.draftRefOrThrow();
632
+ this.head = undefined;
633
+ return this.withObjects(async (objects) => {
634
+ if (!(await objects.origin.resolveRef(ref))) return false;
635
+ await objects.origin.deleteRef({ ref });
636
+ return true;
637
+ });
638
+ }
639
+
640
+ /**
641
+ * Publish the draft as one commit on `main` with `message`, then delete
642
+ * it. When `main` moved since the draft began, the two merge in memory
643
+ * first; a conflict publishes nothing and reports the conflicted files. A
644
+ * draft whose merge leaves `main` as it is publishes nothing. `guard`
645
+ * sees every path the commit changes against `main` and throws to refuse.
646
+ */
647
+ async publish(input: {
648
+ message: string;
649
+ author: { name: string; email: string };
650
+ guard?: (paths: readonly string[]) => void;
651
+ }): Promise<DraftPublishResult> {
652
+ const ref = this.draftRefOrThrow();
653
+ this.head = undefined;
654
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
655
+ const plan = await this.withObjects(
656
+ async (objects): Promise<PublishPlan> => {
657
+ const { draft, main } = await this.tips(objects);
658
+ const nothing = async (): Promise<PublishPlan> => {
659
+ if (draft) await clearDraft(objects, ref, draft);
660
+ return {
661
+ kind: "done",
662
+ done: {
663
+ status: "nothing-to-deploy",
664
+ commitSha: null,
665
+ remoteSha: main,
666
+ conflicts: [],
667
+ },
668
+ };
669
+ };
670
+ if (!draft) return nothing();
671
+ const draftTree = (await objects.commit(draft)).tree;
672
+ if (!main) return { kind: "publish", draft, main, tree: draftTree };
673
+ const { base } = await objects.compare(draft, main);
674
+ const mainTree = (await objects.commit(main)).tree;
675
+ let tree = draftTree;
676
+ if (base !== main) {
677
+ const merged = await mergeTrees({
678
+ objects,
679
+ base: base ? (await objects.commit(base)).tree : null,
680
+ ours: draftTree,
681
+ theirs: mainTree,
682
+ });
683
+ if (merged.status === "conflict")
684
+ return {
685
+ kind: "done",
686
+ done: {
687
+ status: "conflict",
688
+ commitSha: draft,
689
+ remoteSha: main,
690
+ conflicts: merged.conflicts,
691
+ },
692
+ };
693
+ tree = merged.tree;
694
+ }
695
+ if (tree === mainTree) return nothing();
696
+ return { kind: "publish", draft, main, tree };
697
+ },
698
+ );
699
+ if (plan.kind === "done") return plan.done;
700
+ const published = await this.attempt(async (objects) => {
701
+ const mainTree = plan.main
702
+ ? (await objects.commit(plan.main)).tree
703
+ : null;
704
+ input.guard?.(
705
+ (await objects.diffTrees(mainTree, plan.tree)).map(
706
+ (change) => change.path,
707
+ ),
708
+ );
709
+ const sha = await objects.writeCommit({
710
+ tree: plan.tree,
711
+ parents: plan.main ? [plan.main] : [],
712
+ author: input.author,
713
+ message: input.message,
714
+ });
715
+ await objects.origin.updateRef({ ref: MAIN, sha, expected: plan.main });
716
+ await clearDraft(objects, ref, plan.draft);
717
+ return sha;
718
+ });
719
+ if (published)
720
+ return {
721
+ status: "deployed",
722
+ commitSha: published,
723
+ remoteSha: published,
724
+ conflicts: [],
725
+ };
726
+ }
727
+ throw new DraftBusyError();
728
+ }
729
+
730
+ /**
731
+ * Bring what others published into the draft. A draft without changes
732
+ * simply follows `main` again; one with changes gets a merge commit, or
733
+ * the conflicted files when the two cannot be merged (nothing moves).
734
+ */
735
+ async pull(): Promise<MergeResult> {
736
+ return this.mergeMain({});
737
+ }
738
+
739
+ /**
740
+ * Merge `main` into the draft with the member's resolutions for the
741
+ * conflicted files, as one draft commit.
742
+ */
743
+ async resolveConflicts(input: {
744
+ resolutions: Record<string, string>;
745
+ message: string;
746
+ }): Promise<string> {
747
+ const resolutions = Object.fromEntries(
748
+ Object.entries(input.resolutions).map(([file, content]) => [
749
+ normalizePath(file),
750
+ content,
751
+ ]),
752
+ );
753
+ const result = await this.mergeMain({
754
+ resolutions,
755
+ message: input.message,
756
+ });
757
+ if (result.status === "conflict")
758
+ throw new DraftUnresolvedError(result.conflicts);
759
+ if (!result.mergeCommit)
760
+ throw new Error("There is no draft to resolve conflicts in");
761
+ return result.mergeCommit;
762
+ }
763
+
764
+ private async mergeMain(input: {
765
+ resolutions?: Record<string, string>;
766
+ message?: string;
767
+ }): Promise<MergeResult> {
768
+ const ref = this.draftRefOrThrow();
769
+ this.head = undefined;
770
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
771
+ const plan = await this.withObjects(
772
+ async (objects): Promise<MergePlan> => {
773
+ const upToDate = (sha: string | null): MergePlan => ({
774
+ kind: "done",
775
+ result: { status: "up-to-date", mergeCommit: sha, conflicts: [] },
776
+ });
777
+ const { draft, main } = await this.tips(objects);
778
+ if (!draft || !main) return upToDate(draft ?? main);
779
+ const { base } = await objects.compare(draft, main);
780
+ const baseTree = base ? (await objects.commit(base)).tree : null;
781
+ const draftTree = (await objects.commit(draft)).tree;
782
+ const changed =
783
+ (await objects.diffTrees(baseTree, draftTree)).length > 0;
784
+ if (!changed && !input.resolutions) {
785
+ await clearDraft(objects, ref, draft);
786
+ return upToDate(main);
787
+ }
788
+ if (base === main && !input.resolutions) return upToDate(draft);
789
+ const merged = await mergeTrees({
790
+ objects,
791
+ base: baseTree,
792
+ ours: draftTree,
793
+ theirs: (await objects.commit(main)).tree,
794
+ resolutions: input.resolutions,
795
+ });
796
+ if (merged.status === "conflict")
797
+ return {
798
+ kind: "done",
799
+ result: {
800
+ status: "conflict",
801
+ mergeCommit: null,
802
+ conflicts: merged.conflicts,
803
+ },
804
+ };
805
+ return { kind: "merged", draft, main, tree: merged.tree };
806
+ },
807
+ );
808
+ if (plan.kind === "done") return plan.result;
809
+ const sha = await this.attempt(async (objects) => {
810
+ const commit = await objects.writeCommit({
811
+ tree: plan.tree,
812
+ parents: [plan.draft, plan.main],
813
+ author: this.author,
814
+ message: input.message ?? "Merge published changes into draft",
815
+ });
816
+ await objects.origin.updateRef({
817
+ ref,
818
+ sha: commit,
819
+ expected: plan.draft,
820
+ });
821
+ return commit;
822
+ });
823
+ if (sha) return { status: "clean", mergeCommit: sha, conflicts: [] };
824
+ }
825
+ throw new DraftBusyError();
826
+ }
827
+
828
+ async dispose(): Promise<void> {}
829
+ }
830
+
831
+ /**
832
+ * Publish files as one commit on top of `main`, without touching any
833
+ * member's draft (the desktop's publish of a member's local copy). With
834
+ * `base`, the commit the files were edited from, they merge with what was
835
+ * published since, and files changed on both sides are reported as
836
+ * conflicts instead of overwriting. A race with another publisher retries
837
+ * on the new `main`.
838
+ */
839
+ export async function publishFilesToOrigin(input: {
840
+ remote: RemoteBackend;
841
+ cache: GitObjectCache;
842
+ tenantId: string;
843
+ projectId: string;
844
+ files: Record<string, string>;
845
+ base?: string;
846
+ message: string;
847
+ author: { name: string; email: string };
848
+ guard?: (paths: readonly string[]) => void;
849
+ }): Promise<DraftPublishResult> {
850
+ const files = Object.entries(input.files).map(
851
+ ([file, content]) =>
852
+ [normalizePath(file), new TextEncoder().encode(content)] as const,
853
+ );
854
+ const withOrigin = <T>(fn: (objects: OriginObjects) => Promise<T>) =>
855
+ input.remote.withOrigin(input.tenantId, input.projectId, (origin) =>
856
+ fn(new OriginObjects(origin, input.cache)),
857
+ );
858
+ const oids = await withOrigin((objects) =>
859
+ objects.writeBlobs(files.map(([, content]) => content)),
860
+ );
861
+ const changes = new Map<string, TreeChange>();
862
+ files.forEach(([file], index) => {
863
+ const oid = oids[index];
864
+ if (oid) changes.set(file, { oid });
865
+ });
866
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
867
+ const result = await withOrigin(
868
+ async (objects): Promise<DraftPublishResult | null> => {
869
+ const main = await objects.origin.resolveRef(MAIN);
870
+ const mainTree = main ? (await objects.commit(main)).tree : null;
871
+ // Published files follow the project's ignore rules like any write.
872
+ const rules: IgnoreRules = new Map();
873
+ const ignored: string[] = [];
874
+ for (const [file] of changes)
875
+ if (await objects.isIgnored(mainTree, file, rules))
876
+ ignored.push(file);
877
+ if (ignored.length > 0) throw new DraftIgnoredPathError(ignored);
878
+ let tree: string;
879
+ if (input.base && main && input.base !== main) {
880
+ // A base is a commit of the published program, never an id that
881
+ // would let the caller read anything else.
882
+ if (
883
+ !SHA_RE.test(input.base) ||
884
+ !(await objects.isReachable({ sha: input.base, tips: [main] }))
885
+ )
886
+ throw new InvalidBaseError(input.base);
887
+ const baseTree = (await objects.commit(input.base)).tree;
888
+ const merged = await mergeTrees({
889
+ objects,
890
+ base: baseTree,
891
+ ours: await objects.writeTree(baseTree, changes),
892
+ theirs: mainTree ?? baseTree,
893
+ });
894
+ if (merged.status === "conflict")
895
+ return {
896
+ status: "conflict",
897
+ commitSha: input.base,
898
+ remoteSha: main,
899
+ conflicts: merged.conflicts,
900
+ };
901
+ tree = merged.tree;
902
+ } else {
903
+ tree = await objects.writeTree(mainTree, changes);
904
+ }
905
+ if (tree === mainTree)
906
+ return {
907
+ status: "nothing-to-deploy",
908
+ commitSha: null,
909
+ remoteSha: main,
910
+ conflicts: [],
911
+ };
912
+ input.guard?.(
913
+ (await objects.diffTrees(mainTree, tree)).map(
914
+ (change) => change.path,
915
+ ),
916
+ );
917
+ const sha = await objects.writeCommit({
918
+ tree,
919
+ parents: main ? [main] : [],
920
+ author: input.author,
921
+ message: input.message,
922
+ });
923
+ try {
924
+ await objects.origin.updateRef({ ref: MAIN, sha, expected: main });
925
+ } catch (error) {
926
+ if (error instanceof RefMovedError) return null;
927
+ throw error;
928
+ }
929
+ return {
930
+ status: "deployed",
931
+ commitSha: sha,
932
+ remoteSha: sha,
933
+ conflicts: [],
934
+ };
935
+ },
936
+ ).catch((error: unknown) => {
937
+ // The origin itself reports a lost race when it publishes the ref.
938
+ if (error instanceof RefMovedError) return null;
939
+ throw error;
940
+ });
941
+ if (result) return result;
942
+ }
943
+ throw new DraftBusyError();
944
+ }
945
+
946
+ /**
947
+ * The published commit of `branch` as `repo` reads it: straight from the
948
+ * origin for a draft, after fetching it into a checkout otherwise.
949
+ */
950
+ export async function refreshPublished(input: {
951
+ repo: ProjectRepo | OriginDraftRepo;
952
+ remote: RemoteBackend;
953
+ tenantId: string;
954
+ projectId: string;
955
+ branch?: string;
956
+ }): Promise<string | null> {
957
+ const branch = input.branch ?? "main";
958
+ assertValidRefName(`${BRANCHES}${branch}`);
959
+ if (input.repo instanceof OriginDraftRepo)
960
+ return input.remote.withOrigin(input.tenantId, input.projectId, (origin) =>
961
+ origin.resolveRef(`${BRANCHES}${branch}`),
962
+ );
963
+ const fetched = await fetchRemote({
964
+ dev: input.repo,
965
+ remote: input.remote,
966
+ tenantId: input.tenantId,
967
+ projectId: input.projectId,
968
+ remoteBranch: branch,
969
+ });
970
+ return fetched.sha
971
+ ? input.repo.resolveRef(publishedRef(branch)).catch(() => null)
972
+ : null;
973
+ }
974
+
975
+ /**
976
+ * A ref in a private namespace: a session's branch or any member's draft.
977
+ * Compared without case, as a case-insensitive disk would open it.
978
+ */
979
+ function isPrivateRef(ref: string): boolean {
980
+ const lower = ref.toLowerCase();
981
+ return (
982
+ lower.startsWith(SESSION_BRANCHES) ||
983
+ lower.startsWith(`${DRAFT_REF_PREFIX}/`)
984
+ );
985
+ }
986
+
987
+ async function clearDraft(
988
+ objects: OriginObjects,
989
+ ref: string,
990
+ expected: string,
991
+ ): Promise<void> {
992
+ // A write that landed meanwhile keeps the draft: nothing is lost.
993
+ await objects.origin.deleteRef({ ref, expected }).catch((error: unknown) => {
994
+ if (!(error instanceof RefMovedError)) throw error;
995
+ });
996
+ }
997
+
998
+ async function describeChanges(input: {
999
+ objects: OriginObjects;
1000
+ before: string | null;
1001
+ after: string | null;
1002
+ }): Promise<DiffEntry[]> {
1003
+ const decode = async (oid: string | undefined) =>
1004
+ oid ? new TextDecoder().decode(await input.objects.blob(oid)) : null;
1005
+ const changes = await input.objects.diffTrees(input.before, input.after);
1006
+ return Promise.all(
1007
+ changes.map(async (change): Promise<DiffEntry> => {
1008
+ const before = await decode(change.before?.oid);
1009
+ const after = await decode(change.after?.oid);
1010
+ return {
1011
+ path: change.path,
1012
+ kind:
1013
+ before === null ? "added" : after === null ? "deleted" : "modified",
1014
+ before,
1015
+ after,
1016
+ };
1017
+ }),
1018
+ );
1019
+ }
1020
+
1021
+ /**
1022
+ * A project-relative path in canonical form. Absolute paths are refused, as
1023
+ * the file APIs always did, so no spelling slips past path-based policy.
1024
+ */
1025
+ function normalizePath(filePath: string): string {
1026
+ const slashed = filePath.replace(/\\/g, "/");
1027
+ if (slashed.startsWith("/")) throw new Error("Absolute paths not allowed");
1028
+ const normalized = path.posix.normalize(slashed).replace(/^(\.\/)+/, "");
1029
+ assertSafePath(normalized);
1030
+ if (!normalized || normalized === ".")
1031
+ throw new DraftPathError({ code: "EISDIR", path: filePath });
1032
+ return normalized;
1033
+ }