@vite-hub/workspace 0.1.0 → 0.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.
Files changed (134) hide show
  1. package/README.md +164 -107
  2. package/dist/abort-BCwpdrN0.js +32 -0
  3. package/dist/blob-database.d.ts +70 -117
  4. package/dist/blob-database.js +48 -41
  5. package/dist/checkout.d.ts +128 -0
  6. package/dist/checkout.js +849 -0
  7. package/dist/cloudflare.d.ts +2 -2
  8. package/dist/cloudflare.js +1 -1
  9. package/dist/config-B-863EgC.js +15 -0
  10. package/dist/{config-B7dmzDX3.js → config-BAgL2dtB.js} +48 -84
  11. package/dist/{config-DLKdaFWN.d.ts → config-BQKcPawI.d.ts} +1 -1
  12. package/dist/discard-CNNtCozM.js +8 -0
  13. package/dist/durability.d.ts +22 -0
  14. package/dist/durability.js +70 -0
  15. package/dist/error-diagnostics-CtKjGtGb.js +188 -0
  16. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  17. package/dist/file-2pFYNtsU.js +22 -0
  18. package/dist/{files-C7Px8uaC.js → files-BOo4SbwE.js} +2 -2
  19. package/dist/files.d.ts +38 -0
  20. package/dist/files.js +6 -0
  21. package/dist/{github-CPxHtFB7.js → github-CrYp4v8k.js} +32 -5
  22. package/dist/{glob--XcLlcml.js → glob-B8YGvTrZ.js} +4 -5
  23. package/dist/{glob--kNYDbfU.js → glob-Cjxms1t7.js} +1 -1
  24. package/dist/{host-CFnrTXTK.js → host-BFBpXn0N.js} +58 -47
  25. package/dist/{hosted-acMA5XyL.js → hosted-KcUR_jPv.js} +216 -93
  26. package/dist/hosted-vercel-blob-B3-wRdUm.js +410 -0
  27. package/dist/hosted-vercel-blob.d.ts +2 -2
  28. package/dist/hosted-vercel-blob.js +1 -1
  29. package/dist/hosted.d.ts +5 -3
  30. package/dist/hosted.js +2 -2
  31. package/dist/index.d.ts +9 -51
  32. package/dist/index.js +21 -91
  33. package/dist/{lifecycle-BwZ7c9hb.js → lifecycle-B-enk_4A.js} +8 -8
  34. package/dist/lineage.d.ts +26 -0
  35. package/dist/lineage.js +76 -0
  36. package/dist/loader.d.ts +1 -1
  37. package/dist/loader.js +2 -2
  38. package/dist/{mcp-resources-BREFCmtn.js → mcp-resources-DF0F5rcL.js} +2 -2
  39. package/dist/{memory-BbwOqDXl.js → memory-BOexthyW.js} +3 -4
  40. package/dist/{metadata-target-DZEZQGHA.js → metadata-target-CWz6KHKq.js} +17 -16
  41. package/dist/object-Da1zyPCR.js +11 -0
  42. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  43. package/dist/operations-C6FpR8Rr.js +389 -0
  44. package/dist/operations-CE2drFih.js +1234 -0
  45. package/dist/operations.d.ts +41 -4
  46. package/dist/operations.js +3 -2
  47. package/dist/{path-CNAwN7pw.js → path--wrT_Azm.js} +2 -3
  48. package/dist/path-AxMho1wo.d.ts +7 -0
  49. package/dist/{plugins-DqQ8b4T5.d.ts → plugins-C8C0auoW.d.ts} +1 -1
  50. package/dist/{provider-kXjfli9u.js → provider-9s4Ufkm5.js} +104 -82
  51. package/dist/providers/github/store.d.ts +1 -1
  52. package/dist/providers/github/store.js +1 -1
  53. package/dist/registry-B3BBm4Ts.d.ts +19 -0
  54. package/dist/{registry-Bp-8UUfG.js → registry-CNphafBx.js} +55 -20
  55. package/dist/registry-CYNN623b.d.ts +9 -0
  56. package/dist/request-scope-Dw5n8bMC.js +83 -0
  57. package/dist/results-DgkZUmTL.js +8 -0
  58. package/dist/{rolldown-runtime-B4iAMlE-.js → rolldown-runtime-rQ84J-ij.js} +2 -3
  59. package/dist/runtime/assets.d.ts +1 -1
  60. package/dist/runtime/assets.js +3 -3
  61. package/dist/runtime/empty-assets-registry.d.ts +1 -1
  62. package/dist/runtime/empty-registry.d.ts +2 -1
  63. package/dist/runtime/registry.d.ts +2 -0
  64. package/dist/runtime/registry.js +23 -0
  65. package/dist/runtime/request.d.ts +4 -0
  66. package/dist/runtime/request.js +8 -0
  67. package/dist/runtime/state.d.ts +5 -4
  68. package/dist/runtime/state.js +8 -18
  69. package/dist/runtime/workspace.d.ts +1 -1
  70. package/dist/runtime/workspace.js +1 -1
  71. package/dist/runtime.d.ts +9 -8
  72. package/dist/runtime.js +23 -26
  73. package/dist/{search-CrTmXj5h.js → search-C_RfoM2j.js} +2 -2
  74. package/dist/{server-BNQ-Nbjj.js → server-8tGltlGz.js} +53 -40
  75. package/dist/server.d.ts +17 -8
  76. package/dist/server.js +1 -1
  77. package/dist/shared-B3_EUk89.js +848 -0
  78. package/dist/source-metadata.d.ts +6 -2
  79. package/dist/source-metadata.js +8 -8
  80. package/dist/state-BISnUf1s.d.ts +35 -0
  81. package/dist/{ai-BZyLwULx.js → state-DbrW-njQ.js} +96 -54
  82. package/dist/{store-CXgmu-uw.js → store-ybhyD38Z.js} +250 -106
  83. package/dist/{sync-CN6ec-5M.js → sync-CCD_VYC8.js} +4 -4
  84. package/dist/target-jWhTdIuF.js +89 -0
  85. package/dist/test.d.ts +1 -1
  86. package/dist/test.js +1 -1
  87. package/dist/{types-DeK9GIxy.d.ts → types-BbtwmBZ5.d.ts} +68 -14
  88. package/dist/use-C6lV3-wC.d.ts +321 -0
  89. package/dist/{use-BQj7nSz6.js → use-CSpT5W87.js} +75 -82
  90. package/dist/{utils-Blrh4N2n.js → utils-CgMZCHsX.js} +112 -41
  91. package/dist/vite.d.ts +585 -2
  92. package/dist/vite.js +21368 -1
  93. package/dist/{workspace-BWJQBK1u.d.ts → workspace-CYB2xZ1T.d.ts} +1 -1
  94. package/dist/{workspace-6pxkOuxr.js → workspace-sPWn2Jxj.js} +125 -40
  95. package/package.json +46 -55
  96. package/dist/ai-BW2ZhizI.d.ts +0 -177
  97. package/dist/ai.d.ts +0 -3
  98. package/dist/ai.js +0 -2
  99. package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +0 -19
  100. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  101. package/dist/error-diagnostics-DY5GP47p.js +0 -96
  102. package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +0 -354
  103. package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +0 -214
  104. package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +0 -527
  105. package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +0 -248
  106. package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +0 -179
  107. package/dist/file-C0_aPWSS.js +0 -26
  108. package/dist/file-metadata-CxDy-E2H.js +0 -58
  109. package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +0 -2278
  110. package/dist/github-DtncTfmv-Du2S8lGF.js +0 -4159
  111. package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +0 -2530
  112. package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +0 -489
  113. package/dist/hosted-vercel-blob-DKntsHaf.js +0 -12603
  114. package/dist/inspect-BoObD2cJ.js +0 -167
  115. package/dist/mountx.d.ts +0 -8
  116. package/dist/mountx.js +0 -145
  117. package/dist/nitro.d.ts +0 -2
  118. package/dist/nitro.js +0 -2
  119. package/dist/nuxt.d.ts +0 -27
  120. package/dist/nuxt.js +0 -38
  121. package/dist/operations-BcpWr41m.js +0 -159
  122. package/dist/operations-CGqY1XeG.js +0 -965
  123. package/dist/operations-DnOwKsJT.d.ts +0 -136
  124. package/dist/registry-Cg1TJVVZ.d.ts +0 -10
  125. package/dist/request-execution-Dk9rY-Yh.js +0 -84
  126. package/dist/shared-DalXdP0i.js +0 -2158
  127. package/dist/state-B8zbLi5t.d.ts +0 -26
  128. package/dist/target-D4Bqb1eH.js +0 -11
  129. package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +0 -125
  130. package/dist/token-CO62GglH.js +0 -61
  131. package/dist/use-DhwhbAVV.d.ts +0 -108
  132. package/dist/vite-BEvgU2GY.js +0 -20909
  133. package/dist/vite-CcZmMQ7S.d.ts +0 -476
  134. package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +0 -1565
@@ -1,13 +1,15 @@
1
- import { a as workspaceConflict, n as assertWorkspaceDigest, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
2
- import { a as isExcludedWorkspacePath, c as normalizeSafeWorkspacePattern, i as decodeFile, l as normalizeWorkspacePath, n as contentStreamToBytes, r as contentToBytes } from "./path-CNAwN7pw.js";
3
- import { r as workspaceStoreTarget } from "./target-D4Bqb1eH.js";
4
- import { t as workspaceErrorDiagnostics } from "./error-diagnostics-DY5GP47p.js";
5
- import { d as normalizeHistoryRef, l as historyConflict, n as createSnapshotFromEntries, r as diffSnapshots, u as normalizeHistoryPath } from "./utils-Blrh4N2n.js";
6
- import { t as createWorkspaceGlobMatcher } from "./glob--kNYDbfU.js";
7
- import { S as forgeBlob, _ as resolveGitHubRepositoryOption, a as githubBranchMovedConflict, c as joinGitPath, d as readGitHubBranchState, g as resolveGitHubRefsOption, h as resolveGitHubBranchOption, i as gitFileMode, l as readCurrentHead, m as requireGitHubOption, n as connectGitHubRepository, o as githubRequest, p as readGitHubFile, r as gitBlobSha, s as githubRequestStatus, t as commitGitHubChanges, u as readGitHubArchive, v as resolveGitHubRootOption, y as resolveGitHubTokenOption } from "./shared-DalXdP0i.js";
1
+ import { a as workspaceConflict, n as assertWorkspaceDigest, r as isWorkspaceConflict, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
2
+ import { r as workspaceStoreTarget } from "./target-jWhTdIuF.js";
3
+ import { a as isExcludedWorkspacePath, c as normalizeSafeWorkspacePattern, i as decodeFile, l as normalizeWorkspacePath, n as contentStreamToBytes, r as contentToBytes } from "./path--wrT_Azm.js";
4
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
5
+ import { d as normalizeHistoryRef, l as historyConflict, n as createSnapshotFromEntries, r as diffSnapshots, u as normalizeHistoryPath } from "./utils-CgMZCHsX.js";
6
+ import { t as createWorkspaceGlobMatcher } from "./glob-Cjxms1t7.js";
7
+ import { _ as resolveGitHubBranchOption, a as githubBranchMovedConflict, b as resolveGitHubRepositoryOption, c as joinGitPath, d as readCurrentHead, f as readGitHubArchive, g as requireGitHubOption, h as readGitHubFile, i as gitFileMode, l as loadForge, n as connectGitHubRepository, o as githubRequest, p as readGitHubBranchState, r as gitBlobSha, s as githubRequestStatus, t as commitGitHubChanges, u as preloadGitHubFiles, v as resolveGitHubCredential, w as BoundedMap, x as resolveGitHubRootOption, y as resolveGitHubRefsOption } from "./shared-B3_EUk89.js";
8
+ import { t as workspaceStoreDiscard } from "./discard-CNNtCozM.js";
9
+ import { ViteHubError } from "@vite-hub/runtime";
10
+ import { lookup } from "mrmime";
8
11
  import { posix } from "node:path";
9
12
  import { randomUUID } from "node:crypto";
10
- import { lookup } from "mrmime";
11
13
  import * as v from "valibot";
12
14
  //#region src/storage/materialization.ts
13
15
  const workspaceRevisionMaterializer = Symbol.for("vitehub.workspace.revisionMaterializer");
@@ -171,6 +173,30 @@ function isNoHistoryError(error) {
171
173
  const status = githubRequestStatus(error);
172
174
  return status === 404 || status === 409;
173
175
  }
176
+ /**
177
+ * GitHub answers a compare of two commits without a merge base with 404 "No common ancestor between <base> and <head>."
178
+ * Any other failure, such as a 422 "Validation failed, or the endpoint has been spammed", proves nothing.
179
+ */
180
+ function isUnrelatedHistoryError(error) {
181
+ for (let current = error; current instanceof Error; current = current.cause) {
182
+ const body = Reflect.get(current, "body");
183
+ if (/no common ancestor/i.test(`${current.message}\n${typeof body === "string" ? body : ""}`)) return true;
184
+ }
185
+ return false;
186
+ }
187
+ /**
188
+ * GitHub answers a lookup of a commit that the repository does not have with 422 "No commit found for SHA: <sha>." Any
189
+ * other failure, such as a 422 "Validation failed, or the endpoint has been spammed", proves nothing.
190
+ */
191
+ function isMissingCommitError(error) {
192
+ const status = githubRequestStatus(error);
193
+ if (status !== 404 && status !== 422) return false;
194
+ for (let current = error; current instanceof Error; current = current.cause) {
195
+ const body = Reflect.get(current, "body");
196
+ if (/no commit found for/i.test(`${current.message}\n${typeof body === "string" ? body : ""}`)) return true;
197
+ }
198
+ return false;
199
+ }
174
200
  function cursorFor(ref, id) {
175
201
  return `${ref}:after:${id}`;
176
202
  }
@@ -218,6 +244,20 @@ function readCommitMessage(message) {
218
244
  metadata
219
245
  };
220
246
  }
247
+ /**
248
+ * The Git author of a history commit: `metadata.author` with a `name` and an `email`, as Content and the
249
+ * `workspace.commit` operation record the signed-in user. Without both, the account of the token is the author.
250
+ */
251
+ function commitAuthor(metadata) {
252
+ const author = metadata?.author;
253
+ if (!author || typeof author !== "object") return void 0;
254
+ const name = Reflect.get(author, "name");
255
+ const email = Reflect.get(author, "email");
256
+ return typeof name === "string" && name.trim() && typeof email === "string" && email.trim() ? {
257
+ name,
258
+ email
259
+ } : void 0;
260
+ }
221
261
  function messageWithMetadata(message, metadata) {
222
262
  const limit = (what, size, max) => {
223
263
  if (size > max) throw workspaceErrorDiagnostics.WORKSPACE_R0073({ message: `[vitehub] GitHub history commit ${what} is ${size} bytes, over the limit of ${max}. Shorten it.` });
@@ -229,6 +269,7 @@ function messageWithMetadata(message, metadata) {
229
269
  limit("metadata", new TextEncoder().encode(json).byteLength, githubMaxMetadataBytes);
230
270
  return `${message}\n\n${metadataTrailer}${json}`;
231
271
  }
272
+ /** A revision from its commit. Without `entries`, the revision leaves out `files` and `bytes`. */
232
273
  function publicRevision(commit, ref, entries, url, suppliedMetadata) {
233
274
  const stored = readCommitMessage(commit.message);
234
275
  suppliedMetadata ??= stored.metadata;
@@ -256,8 +297,10 @@ function publicRevision(commit, ref, entries, url, suppliedMetadata) {
256
297
  createdAt: createdAt.toISOString(),
257
298
  ...stored.message ? { message: stored.message } : {},
258
299
  ...metadata ? { metadata } : {},
259
- files: entries.length,
260
- bytes: entries.reduce((total, entry) => total + entry.size, 0)
300
+ ...entries ? {
301
+ files: entries.length,
302
+ bytes: entries.reduce((total, entry) => total + entry.size, 0)
303
+ } : {}
261
304
  };
262
305
  }
263
306
  function viewPath(path) {
@@ -335,9 +378,9 @@ function createGitHubWorkspaceHistory(input) {
335
378
  };
336
379
  const hiddenBranch = (branch) => toBranch(fromBranch(branch)) !== branch;
337
380
  const heads = /* @__PURE__ */ new Map();
338
- const commitCache = /* @__PURE__ */ new Map();
339
- const treeCache = /* @__PURE__ */ new Map();
340
- const commitRefs = /* @__PURE__ */ new Map();
381
+ const commitCache = new BoundedMap(2e3);
382
+ const treeCache = new BoundedMap(32);
383
+ const commitRefs = new BoundedMap(2e3);
341
384
  const readCommit = async (id) => {
342
385
  const cached = commitCache.get(id);
343
386
  if (cached) return cached;
@@ -401,6 +444,13 @@ function createGitHubWorkspaceHistory(input) {
401
444
  commitRefs.set(commit.sha, ref);
402
445
  return publicRevision(commit, ref, entries, `https://github.com/${options.repository}/commit/${commit.sha}`, suppliedMetadata);
403
446
  };
447
+ /** A revision from a commit that a list or a head read returned, without the tree request that `files` and `bytes` need. */
448
+ const listedRevision = (ref, commit) => {
449
+ if (!nonEmptyString(commit.sha)) malformed("commit list");
450
+ commitCache.set(commit.sha, commit);
451
+ commitRefs.set(commit.sha, ref);
452
+ return publicRevision(commit, ref, void 0, `https://github.com/${options.repository}/commit/${commit.sha}`);
453
+ };
404
454
  const readBranches = async () => {
405
455
  try {
406
456
  return await githubRequest(client(), async (provider, repo) => {
@@ -424,7 +474,15 @@ function createGitHubWorkspaceHistory(input) {
424
474
  if (cached && cached.expires > Date.now()) return await cached.head;
425
475
  const head = (async () => {
426
476
  try {
427
- return await githubRequest(client(), async (provider, repo) => await provider.contents.resolveRef(repo, `heads/${branch}`), "commit");
477
+ const commit = await githubRequest(client(), async (provider, repo) => await provider.commits.get({
478
+ forge: provider.forge,
479
+ instance: provider.instance,
480
+ repo,
481
+ sha: encodeURIComponent(`heads/${branch}`)
482
+ }), "commit");
483
+ if (!nonEmptyString(commit.sha)) malformed("commit");
484
+ commitCache.set(commit.sha, commit);
485
+ return commit.sha;
428
486
  } catch (error) {
429
487
  if (isNoHistoryError(error) || githubRequestStatus(error) === 422) return null;
430
488
  throw error;
@@ -439,6 +497,22 @@ function createGitHubWorkspaceHistory(input) {
439
497
  });
440
498
  return await head;
441
499
  };
500
+ /** Whether the history of `branch` has the commit `id`: the commit is the merge base of both. */
501
+ async function branchContains(branch, id) {
502
+ if (!/^[0-9a-f]{40}$/i.test(id)) return false;
503
+ const head = await readBranchHead(branch);
504
+ if (!head) return false;
505
+ if (head.toLowerCase() === id.toLowerCase()) return true;
506
+ return await githubRequest(client(), async (provider, repo) => {
507
+ try {
508
+ const compare = (await provider.request("GET", `${repoPath(repo)}/compare/${encodeURIComponent(head)}...${encodeURIComponent(id)}`, { query: { per_page: 1 } })).data;
509
+ return String(Reflect.get(Object(Reflect.get(Object(compare), "merge_base_commit")), "sha")).toLowerCase() === id.toLowerCase();
510
+ } catch (error) {
511
+ if (isUnrelatedHistoryError(error) || githubRequestStatus(error) === 404) return false;
512
+ throw error;
513
+ }
514
+ }, "compare");
515
+ }
442
516
  const list = async (listOptions = {}) => {
443
517
  const { branch, ref } = resolveRef(listOptions.ref);
444
518
  const limit = listOptions.limit ?? 20;
@@ -447,7 +521,10 @@ function createGitHubWorkspaceHistory(input) {
447
521
  const revisionCursor = separator < 0 ? void 0 : listOptions.cursor.slice(separator + 7);
448
522
  if (revisionCursor !== void 0 && (listOptions.cursor.slice(0, separator) !== ref || !revisionCursor)) throw workspaceErrorDiagnostics.WORKSPACE_R0070({ message: `[vitehub] History cursor does not belong to ref "${ref}".` });
449
523
  const afterId = revisionCursor ?? (listOptions.cursor && /^[0-9a-f]{40}$/i.test(listOptions.cursor) ? listOptions.cursor : void 0);
524
+ if (afterId !== void 0 && !await branchContains(branch, afterId)) throw workspaceErrorDiagnostics.WORKSPACE_R0070({ message: `[vitehub] History cursor does not belong to ref "${ref}".` });
450
525
  const page = afterId ? 1 : pageFromCursor(ref, listOptions.cursor);
526
+ const start = afterId ?? (page === 1 ? await readBranchHead(branch) : branch);
527
+ if (!start) return { revisions: [] };
451
528
  const gitPath = !listOptions.path ? "" : joinGitPath(options.root, normalizeHistoryPath(listOptions.path));
452
529
  let result;
453
530
  try {
@@ -456,7 +533,7 @@ function createGitHubWorkspaceHistory(input) {
456
533
  return await provider.commits.list(repo, {
457
534
  cursor,
458
535
  perPage: afterId ? Math.min(limit + 1, 100) : limit,
459
- ref: afterId ?? branch,
536
+ ref: start,
460
537
  ...gitPath ? { path: gitPath } : {}
461
538
  }).page();
462
539
  }, "commit list");
@@ -466,10 +543,7 @@ function createGitHubWorkspaceHistory(input) {
466
543
  }
467
544
  const items = afterId && result.items[0]?.sha === afterId ? result.items.slice(1) : result.items;
468
545
  const shown = items.slice(0, limit);
469
- const revisions = await Promise.all(shown.map((commit) => {
470
- if (!nonEmptyString(commit.sha)) malformed("commit list");
471
- return revision(ref, commit.sha);
472
- }));
546
+ const revisions = shown.map((commit) => listedRevision(ref, commit));
473
547
  const followingPage = nextPage(result.cursor?.nextUrl);
474
548
  if (afterId) {
475
549
  const last = shown.at(-1)?.sha;
@@ -500,12 +574,14 @@ function createGitHubWorkspaceHistory(input) {
500
574
  if (!branch) {
501
575
  const ordered = [...branches].sort((left, right) => Number(right.name === options.branch) - Number(left.name === options.branch));
502
576
  for (const candidate of ordered) if (await githubRequest(client(), async (provider, repo) => {
503
- for await (const commit of provider.commits.list(repo, {
504
- ref: candidate.name,
505
- perPage: 100
506
- })) if (commit.sha === id) return true;
507
- return false;
508
- }, "commit list")) {
577
+ try {
578
+ const compare = (await provider.request("GET", `${repoPath(repo)}/compare/${encodeURIComponent(candidate.commit)}...${encodeURIComponent(id)}`, { query: { per_page: 1 } })).data;
579
+ return Reflect.get(Object(Reflect.get(Object(compare), "merge_base_commit")), "sha") === id;
580
+ } catch (error) {
581
+ if (isUnrelatedHistoryError(error)) return false;
582
+ throw error;
583
+ }
584
+ }, "compare")) {
509
585
  branch = candidate;
510
586
  break;
511
587
  }
@@ -520,8 +596,7 @@ function createGitHubWorkspaceHistory(input) {
520
596
  try {
521
597
  commit = await readCommit(id);
522
598
  } catch (error) {
523
- const status = githubRequestStatus(error);
524
- if (status === 404 || status === 422) throw workspaceError(`[vitehub] Workspace revision does not exist: ${id}.`);
599
+ if (isMissingCommitError(error)) throw new ViteHubError("WORKSPACE_NOT_FOUND", `[vitehub] Workspace revision does not exist: ${id}.`, { cause: error });
525
600
  throw error;
526
601
  }
527
602
  const ref = await refForCommit(commit.sha);
@@ -581,6 +656,16 @@ function createGitHubWorkspaceHistory(input) {
581
656
  path: joinGitPath(options.root, normalized)
582
657
  }, commit.sha);
583
658
  return decodeFile(bytes, readOptions);
659
+ },
660
+ preload: async (paths) => {
661
+ const entries = paths.flatMap((path) => {
662
+ const entry = byPath.get(normalizeHistoryPath(path));
663
+ return entry ? [{
664
+ ...entry,
665
+ path: joinGitPath(options.root, entry.path)
666
+ }] : [];
667
+ });
668
+ await preloadGitHubFiles(client(), commit.sha, entries);
584
669
  }
585
670
  });
586
671
  };
@@ -672,9 +757,13 @@ function createGitHubWorkspaceHistory(input) {
672
757
  deletePaths: deletes,
673
758
  files: updates,
674
759
  message: messageWithMetadata(commitOptions.message || "Update Workspace", commitOptions.metadata),
760
+ author: commitAuthor(commitOptions.metadata),
675
761
  parentSha: state.refSha,
676
762
  remoteModes: new Map([...state.files.values()].map((entry) => [entry.path, entry.mode])),
677
763
  repository: client()
764
+ }).catch((error) => {
765
+ if (isWorkspaceConflict(error)) heads.delete(branch);
766
+ throw error;
678
767
  });
679
768
  heads.set(branch, {
680
769
  expires: Date.now() + githubHeadCacheMs,
@@ -900,7 +989,7 @@ function createGitHubWorkspaceHistory(input) {
900
989
  base: b?.sha ?? null
901
990
  });
902
991
  }
903
- const resolution = await mergeOptions.onConflict(conflicts, { read: async (sha) => await forgeBlob(provider, repo, sha) });
992
+ const resolution = await mergeOptions.onConflict(conflicts, { read: async (sha) => await (await loadForge()).forgeBlob(provider, repo, sha) });
904
993
  metadata = {
905
994
  ...mergeOptions.metadata,
906
995
  ...resolution.metadata
@@ -1065,7 +1154,7 @@ function createGitHubWorkspaceHistory(input) {
1065
1154
  head: async (headOptions) => {
1066
1155
  const { branch, ref } = resolveRef(headOptions?.ref);
1067
1156
  const id = await readBranchHead(branch);
1068
- return id ? await revision(ref, id) : null;
1157
+ return id ? listedRevision(ref, await readCommit(id)) : null;
1069
1158
  },
1070
1159
  digest: gitBlobSha,
1071
1160
  forksFrom: async (ref) => options.refs?.published && ref !== "published" ? "published" : void 0,
@@ -1193,6 +1282,7 @@ var GitHubWorkspaceStore = class {
1193
1282
  #baselineRefSha;
1194
1283
  #dirty = false;
1195
1284
  #files = /* @__PURE__ */ new Map();
1285
+ #loadedAt = 0;
1196
1286
  #mutationQueue = Promise.resolve();
1197
1287
  #ready;
1198
1288
  #remoteFiles = /* @__PURE__ */ new Map();
@@ -1210,10 +1300,9 @@ var GitHubWorkspaceStore = class {
1210
1300
  get #connection() {
1211
1301
  return this.#resolved ||= (() => {
1212
1302
  const repository = requireGitHubOption("a repository", resolveGitHubRepositoryOption(this.options));
1213
- const token = requireGitHubOption("a token", resolveGitHubTokenOption(this.options));
1214
1303
  return {
1215
1304
  branch: resolveGitHubBranchOption(this.options),
1216
- client: connectGitHubRepository(repository, token),
1305
+ client: connectGitHubRepository(repository, resolveGitHubCredential(this.options)),
1217
1306
  repository,
1218
1307
  root: resolveGitHubRootOption(this.options, this.workspaceName)
1219
1308
  };
@@ -1240,6 +1329,13 @@ var GitHubWorkspaceStore = class {
1240
1329
  root: this.#root
1241
1330
  }));
1242
1331
  }
1332
+ /** Drops the staged writes. The next call loads the branch again, as the first call does. */
1333
+ async [workspaceStoreDiscard]() {
1334
+ await this.#mutate(async () => {
1335
+ this.#dirty = false;
1336
+ this.#ready = void 0;
1337
+ });
1338
+ }
1243
1339
  [workspaceStoreTarget]() {
1244
1340
  return {
1245
1341
  provider: "github",
@@ -1283,13 +1379,13 @@ var GitHubWorkspaceStore = class {
1283
1379
  };
1284
1380
  async readFile(path) {
1285
1381
  const normalized = normalizeSafeWorkspacePath(path);
1286
- await this.#ensure({ refresh: false });
1382
+ await this.#mutate(async () => await this.#ensure({ refresh: "expired" }));
1287
1383
  return await this.#readWorkspaceFile(normalized);
1288
1384
  }
1289
1385
  async writeFile(path, file) {
1290
1386
  await this.#mutate(async () => {
1291
1387
  const normalized = normalizeSafeWorkspacePath(path);
1292
- await this.#ensure({ refresh: false });
1388
+ await this.#ensure({ refresh: "expired" });
1293
1389
  await this.#writeFile(normalized, file);
1294
1390
  });
1295
1391
  }
@@ -1383,7 +1479,7 @@ var GitHubWorkspaceStore = class {
1383
1479
  async rm(path, options = {}) {
1384
1480
  await this.#mutate(async () => {
1385
1481
  const normalized = normalizeSafeWorkspacePath(path);
1386
- await this.#ensure({ refresh: false });
1482
+ await this.#ensure({ refresh: "expired" });
1387
1483
  const file = this.#files.get(normalized);
1388
1484
  if (options.ifDigest !== void 0) assertWorkspaceDigest(path, options.ifDigest, file ? (await this.#fileEntry(file)).digest : void 0);
1389
1485
  const removedFile = Boolean(file && !isReservedWorkspacePath(normalized));
@@ -1408,61 +1504,80 @@ var GitHubWorkspaceStore = class {
1408
1504
  async rebase(options = {}) {
1409
1505
  await this.#mutate(async () => {
1410
1506
  await this.#ensure({ refresh: false });
1411
- const remote = await readGitHubBranchState({
1412
- branch: this.#branch,
1413
- repository: this.#client,
1414
- root: this.#root
1415
- });
1416
- const remoteFiles = new Map([...remote.files].filter(([path]) => !isFileMetadataPath(path)));
1417
- const remoteMetadataFiles = new Map([...remote.files].filter(([path]) => isFileMetadataPath(path)));
1418
- const remoteAttributes = /* @__PURE__ */ new Map();
1419
- await Promise.all([...remoteMetadataFiles].map(async ([path, entry]) => {
1420
- const bytes = await readGitHubFile(this.#client, entry, remote.refSha);
1421
- remoteAttributes.set(filePathFromMetadataPath(path), parseFileAttributes(bytes));
1422
- }));
1423
- const takeRemote = options.takeRemote || [];
1424
- const shouldTakeRemote = (path) => takeRemote.some((root) => path === root || path.startsWith(`${root}/`));
1425
- const local = new Map(this.#files);
1426
- const previousRemoteFiles = this.#remoteFiles;
1427
- const previousRemoteMetadataFiles = this.#remoteMetadataFiles;
1428
- const changed = /* @__PURE__ */ new Set([...previousRemoteFiles.keys(), ...local.keys()]);
1429
- if (remote.refSha === this.#baselineRefSha) {
1430
- for (const path of changed) {
1431
- if (!shouldTakeRemote(path)) continue;
1432
- const file = remoteFiles.get(path);
1433
- if (file) this.#files.set(path, githubRemoteFile(path, file, remoteAttributes.get(path)));
1434
- else this.#files.delete(path);
1435
- }
1436
- this.#dirty = await this.#hasRemoteChanges();
1437
- return;
1438
- }
1439
- for (const path of changed) {
1440
- if (await this.#matchesRemote(local.get(path), previousRemoteFiles.get(path), previousRemoteMetadataFiles.get(fileMetadataPath(path)))) {
1441
- changed.delete(path);
1442
- continue;
1443
- }
1444
- const previous = previousRemoteFiles.get(path);
1445
- const current = remoteFiles.get(path);
1446
- const previousMetadata = previousRemoteMetadataFiles.get(fileMetadataPath(path));
1447
- const currentMetadata = remoteMetadataFiles.get(fileMetadataPath(path));
1448
- if ((!sameGitHubTreeEntry(previous, current) || !sameGitHubTreeEntry(previousMetadata, currentMetadata)) && !shouldTakeRemote(path) && !await this.#matchesRemote(local.get(path), current, currentMetadata)) throw workspaceConflict(`[vitehub] GitHub Workspace Store rebase conflict for ${this.#repository}@${this.#branch}: ${path} changed locally and remotely.`);
1449
- }
1450
- this.#baselineRefSha = remote.refSha;
1451
- this.#remoteFiles = remoteFiles;
1452
- this.#remoteMetadataFiles = remoteMetadataFiles;
1453
- this.#files = new Map([...remoteFiles].map(([path, entry]) => [path, githubRemoteFile(path, entry, remoteAttributes.get(path))]));
1454
- this.#baseline = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }, false), "github-workspace-store-rebase");
1507
+ await this.#rebase(options);
1508
+ });
1509
+ }
1510
+ /** Move the staged writes onto the current branch head. A path that changed on both sides fails with its name in `details.paths`. */
1511
+ async #rebase(options, loaded) {
1512
+ const remote = loaded ?? await readGitHubBranchState({
1513
+ branch: this.#branch,
1514
+ repository: this.#client,
1515
+ root: this.#root
1516
+ });
1517
+ const remoteFiles = new Map([...remote.files].filter(([path]) => !isFileMetadataPath(path)));
1518
+ const remoteMetadataFiles = new Map([...remote.files].filter(([path]) => isFileMetadataPath(path)));
1519
+ const remoteAttributes = /* @__PURE__ */ new Map();
1520
+ await Promise.all([...remoteMetadataFiles].map(async ([path, entry]) => {
1521
+ const bytes = await readGitHubFile(this.#client, entry, remote.refSha);
1522
+ remoteAttributes.set(filePathFromMetadataPath(path), parseFileAttributes(bytes));
1523
+ }));
1524
+ const takeRemote = options.takeRemote || [];
1525
+ const shouldTakeRemote = (path) => takeRemote.some((root) => path === root || path.startsWith(`${root}/`));
1526
+ const local = new Map(this.#files);
1527
+ const previousRemoteFiles = this.#remoteFiles;
1528
+ const previousRemoteMetadataFiles = this.#remoteMetadataFiles;
1529
+ const changed = /* @__PURE__ */ new Set([...previousRemoteFiles.keys(), ...local.keys()]);
1530
+ if (remote.refSha === this.#baselineRefSha) {
1455
1531
  for (const path of changed) {
1456
- if (shouldTakeRemote(path)) continue;
1457
- const file = local.get(path);
1458
- if (file) this.#files.set(path, file);
1532
+ if (!shouldTakeRemote(path)) continue;
1533
+ const file = remoteFiles.get(path);
1534
+ if (file) this.#files.set(path, githubRemoteFile(path, file, remoteAttributes.get(path)));
1459
1535
  else this.#files.delete(path);
1460
1536
  }
1461
1537
  this.#dirty = await this.#hasRemoteChanges();
1462
- });
1538
+ return;
1539
+ }
1540
+ const conflicts = [];
1541
+ for (const path of changed) {
1542
+ if (await this.#matchesRemote(local.get(path), previousRemoteFiles.get(path), previousRemoteMetadataFiles.get(fileMetadataPath(path)))) {
1543
+ changed.delete(path);
1544
+ continue;
1545
+ }
1546
+ const previous = previousRemoteFiles.get(path);
1547
+ const current = remoteFiles.get(path);
1548
+ const previousMetadata = previousRemoteMetadataFiles.get(fileMetadataPath(path));
1549
+ const currentMetadata = remoteMetadataFiles.get(fileMetadataPath(path));
1550
+ if ((!sameGitHubTreeEntry(previous, current) || !sameGitHubTreeEntry(previousMetadata, currentMetadata)) && !shouldTakeRemote(path) && !await this.#matchesRemote(local.get(path), current, currentMetadata)) conflicts.push(path);
1551
+ }
1552
+ if (conflicts.length) {
1553
+ conflicts.sort();
1554
+ throw workspaceConflict(`[vitehub] GitHub Workspace Store rebase conflict for ${this.#repository}@${this.#branch}: ${conflicts.join(", ")} changed locally and remotely.`, { details: {
1555
+ branch: this.#branch,
1556
+ paths: conflicts,
1557
+ repository: this.#repository
1558
+ } });
1559
+ }
1560
+ this.#baselineRefSha = remote.refSha;
1561
+ this.#loadedAt = Date.now();
1562
+ this.#remoteFiles = remoteFiles;
1563
+ this.#remoteMetadataFiles = remoteMetadataFiles;
1564
+ this.#files = new Map([...remoteFiles].map(([path, entry]) => [path, githubRemoteFile(path, entry, remoteAttributes.get(path))]));
1565
+ this.#baseline = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }, false), "github-workspace-store-rebase");
1566
+ for (const path of changed) {
1567
+ if (shouldTakeRemote(path)) continue;
1568
+ const file = local.get(path);
1569
+ if (file) this.#files.set(path, file);
1570
+ else this.#files.delete(path);
1571
+ }
1572
+ this.#dirty = await this.#hasRemoteChanges();
1463
1573
  }
1464
- async #snapshot(options) {
1465
- await this.#ensure({ refresh: false });
1574
+ /**
1575
+ * Commit the staged writes. When the branch moved since the Store loaded, for example because another isolate
1576
+ * committed, the Store moves the staged writes onto the new head and commits once more. A path that changed on
1577
+ * both sides, or a second move, fails with `WORKSPACE_CONFLICT`.
1578
+ */
1579
+ async #snapshot(options, retry = true) {
1580
+ await this.#ensure({ refresh: "expired" });
1466
1581
  const snapshot = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }), options.name);
1467
1582
  if (!this.#dirty) {
1468
1583
  this.#baseline = snapshot;
@@ -1473,12 +1588,18 @@ var GitHubWorkspaceStore = class {
1473
1588
  repository: this.#client,
1474
1589
  root: this.#root
1475
1590
  });
1476
- if (this.#baselineRefSha && remote.refSha !== this.#baselineRefSha) throw githubBranchMovedConflict({
1477
- actualHead: remote.refSha,
1478
- branch: this.#branch,
1479
- expectedHead: this.#baselineRefSha,
1480
- repository: this.#repository
1481
- });
1591
+ if (this.#baselineRefSha && remote.refSha !== this.#baselineRefSha) {
1592
+ if (retry) {
1593
+ await this.#rebase({}, remote);
1594
+ return await this.#snapshot(options, false);
1595
+ }
1596
+ throw githubBranchMovedConflict({
1597
+ actualHead: remote.refSha,
1598
+ branch: this.#branch,
1599
+ expectedHead: this.#baselineRefSha,
1600
+ repository: this.#repository
1601
+ });
1602
+ }
1482
1603
  const remoteFiles = new Map([...remote.files].filter(([path]) => !isFileMetadataPath(path)));
1483
1604
  const remoteMetadataFiles = new Map([...remote.files].filter(([path]) => isFileMetadataPath(path)));
1484
1605
  this.#remoteFiles = remoteFiles;
@@ -1510,18 +1631,27 @@ var GitHubWorkspaceStore = class {
1510
1631
  mode: "100644"
1511
1632
  });
1512
1633
  }
1513
- const commitSha = await commitGitHubChanges({
1514
- branch: this.#branch,
1515
- branchExists: remote.branchExists,
1516
- deletePaths,
1517
- files,
1518
- message: options.name || "chore: update workspace snapshot",
1519
- parentSha: this.#baselineRefSha,
1520
- remoteModes: new Map([...this.#remoteFiles.values()].map((entry) => [entry.path, entry.mode])),
1521
- repository: this.#client
1522
- });
1634
+ let commitSha;
1635
+ try {
1636
+ commitSha = await commitGitHubChanges({
1637
+ branch: this.#branch,
1638
+ branchExists: remote.branchExists,
1639
+ deletePaths,
1640
+ files,
1641
+ message: options.name || "chore: update workspace snapshot",
1642
+ ...options.author ? { author: options.author } : {},
1643
+ parentSha: this.#baselineRefSha,
1644
+ remoteModes: new Map([...this.#remoteFiles.values()].map((entry) => [entry.path, entry.mode])),
1645
+ repository: this.#client
1646
+ });
1647
+ } catch (error) {
1648
+ if (!retry || !isWorkspaceConflict(error)) throw error;
1649
+ await this.#rebase({});
1650
+ return await this.#snapshot(options, false);
1651
+ }
1523
1652
  this.#dirty = false;
1524
1653
  this.#baselineRefSha = commitSha;
1654
+ this.#loadedAt = Date.now();
1525
1655
  this.#remoteFiles = this.#toRemoteFiles();
1526
1656
  this.#remoteMetadataFiles = await this.#toRemoteMetadataFiles();
1527
1657
  this.#baseline = {
@@ -1552,16 +1682,19 @@ var GitHubWorkspaceStore = class {
1552
1682
  return await this.#mutate(async () => {
1553
1683
  await this.#ensure({ refresh: true });
1554
1684
  const file = await this.#readWorkspaceFile(this.#metaPath(key));
1555
- if (!file) return void 0;
1685
+ if (!file?.bytes.byteLength) return void 0;
1556
1686
  return JSON.parse(new TextDecoder().decode(file.bytes));
1557
1687
  });
1558
1688
  }
1559
1689
  async setMeta(key, value) {
1560
1690
  await this.#mutate(async () => {
1561
1691
  const path = this.#metaPath(key);
1562
- const content = JSON.stringify(value);
1563
- const bytes = new TextEncoder().encode(content);
1564
- await this.#ensure({ refresh: false });
1692
+ await this.#ensure({ refresh: "expired" });
1693
+ if (value === void 0) {
1694
+ if (this.#files.delete(path)) this.#dirty = true;
1695
+ return;
1696
+ }
1697
+ const bytes = new TextEncoder().encode(JSON.stringify(value));
1565
1698
  this.#files.set(path, {
1566
1699
  bytes,
1567
1700
  gitSha: await gitBlobSha(bytes),
@@ -1571,11 +1704,21 @@ var GitHubWorkspaceStore = class {
1571
1704
  this.#dirty = true;
1572
1705
  });
1573
1706
  }
1707
+ /**
1708
+ * Load the branch once. Without staged writes, `refresh: true` reads the head again, and `"expired"` reads it again
1709
+ * when the Store loaded it more than `githubHeadCacheMs` ago. A Store that one isolate keeps for many requests so
1710
+ * sees commits from other writers before it stages new writes.
1711
+ */
1574
1712
  async #ensure(options) {
1575
1713
  const wasReady = !!this.#ready;
1576
- this.#ready ||= this.#load();
1714
+ this.#ready ||= this.#load().catch((error) => {
1715
+ this.#ready = void 0;
1716
+ throw error;
1717
+ });
1577
1718
  await this.#ready;
1578
- if (wasReady && options.refresh && !this.#dirty) await this.#load();
1719
+ if (!wasReady || this.#dirty || !options.refresh) return;
1720
+ if (options.refresh === "expired" && Date.now() - this.#loadedAt < 5e3) return;
1721
+ await this.#load();
1579
1722
  }
1580
1723
  async #matchesRemote(file, remote, remoteMetadata) {
1581
1724
  if (!matchesGitHubRemote(file, remote)) return false;
@@ -1596,6 +1739,7 @@ var GitHubWorkspaceStore = class {
1596
1739
  root: this.#root
1597
1740
  });
1598
1741
  this.#baselineRefSha = remote.refSha;
1742
+ this.#loadedAt = Date.now();
1599
1743
  const remoteFiles = new Map([...remote.files].filter(([path]) => !isFileMetadataPath(path)));
1600
1744
  const remoteMetadataFiles = new Map([...remote.files].filter(([path]) => isFileMetadataPath(path)));
1601
1745
  const attributes = /* @__PURE__ */ new Map();
@@ -1,8 +1,8 @@
1
1
  import { s as workspaceError } from "./path-DrSIenjj.js";
2
- import { f as sha256, n as contentStreamToBytes } from "./path-CNAwN7pw.js";
3
- import { a as normalizeWorkspaceSources, f as prepareWorkspaceSource, n as createSourceContext, s as sourceMountContainsPath } from "./config-B7dmzDX3.js";
4
- import { d as sourceSyncPathClaims, f as workspaceSourceSyncStateEquals, l as readWorkspaceSourceSyncState, u as sourceSyncMetaKey } from "./workspace-6pxkOuxr.js";
5
- import { C as withWorkspaceStoreMutation, E as normalizeSourceFileMetadata, S as sourceMountOwnsPath, T as normalizeMetadataValue, w as normalizeSourceItemPath, x as createWorkspaceSourceMountAuthority } from "./metadata-target-DZEZQGHA.js";
2
+ import { f as sha256, n as contentStreamToBytes } from "./path--wrT_Azm.js";
3
+ import { d as sourceSyncPathClaims, f as workspaceSourceSyncStateEquals, l as readWorkspaceSourceSyncState, u as sourceSyncMetaKey } from "./workspace-sPWn2Jxj.js";
4
+ import { a as normalizeWorkspaceSources, f as prepareWorkspaceSource, n as createSourceContext, s as sourceMountContainsPath } from "./config-BAgL2dtB.js";
5
+ import { C as withWorkspaceStoreMutation, E as normalizeSourceFileMetadata, S as sourceMountOwnsPath, T as normalizeMetadataValue, w as normalizeSourceItemPath, x as createWorkspaceSourceMountAuthority } from "./metadata-target-CWz6KHKq.js";
6
6
  //#region src/sources/sync.ts
7
7
  const sourceSyncLocks = /* @__PURE__ */ new Map();
8
8
  const sourceSyncGrants = createWorkspaceSourceMountAuthority("Source Sync");