@vite-hub/workspace 0.0.3 → 0.1.0

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 (129) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +236 -58
  3. package/dist/{ai-nmHdzjCM.d.ts → ai-BW2ZhizI.d.ts} +22 -7
  4. package/dist/{ai-Ce3PtWFW.js → ai-BZyLwULx.js} +147 -66
  5. package/dist/ai.d.ts +2 -2
  6. package/dist/ai.js +1 -1
  7. package/dist/{asset-registry-CaG9b7tf.js → asset-registry-DfBV5kmw.js} +3 -2
  8. package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +19 -0
  9. package/dist/blob-database.d.ts +521 -0
  10. package/dist/blob-database.js +601 -0
  11. package/dist/cloudflare.d.ts +5 -6
  12. package/dist/cloudflare.js +1 -1
  13. package/dist/config-B7dmzDX3.js +1112 -0
  14. package/dist/{config-3I1BnsdO.d.ts → config-DLKdaFWN.d.ts} +1 -2
  15. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  16. package/dist/error-diagnostics-DY5GP47p.js +96 -0
  17. package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +354 -0
  18. package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +214 -0
  19. package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +527 -0
  20. package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +248 -0
  21. package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +179 -0
  22. package/dist/file-C0_aPWSS.js +26 -0
  23. package/dist/file-metadata-CxDy-E2H.js +58 -0
  24. package/dist/{files-QRV55OCx.js → files-C7Px8uaC.js} +21 -10
  25. package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +2278 -0
  26. package/dist/{github-CfA5vpJ5.js → github-CPxHtFB7.js} +36 -34
  27. package/dist/github-DtncTfmv-Du2S8lGF.js +4159 -0
  28. package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +2530 -0
  29. package/dist/glob--XcLlcml.js +22 -0
  30. package/dist/glob--kNYDbfU.js +30 -0
  31. package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +489 -0
  32. package/dist/host-CFnrTXTK.js +1086 -0
  33. package/dist/{hosted-C1-tTTTf.js → hosted-acMA5XyL.js} +216 -43
  34. package/dist/hosted-vercel-blob-DKntsHaf.js +12603 -0
  35. package/dist/hosted-vercel-blob.d.ts +5 -6
  36. package/dist/hosted-vercel-blob.js +1 -1
  37. package/dist/hosted.d.ts +6 -7
  38. package/dist/hosted.js +1 -1
  39. package/dist/index.d.ts +76 -64
  40. package/dist/index.js +162 -457
  41. package/dist/inspect-BoObD2cJ.js +167 -0
  42. package/dist/internal/path.d.ts +2 -0
  43. package/dist/internal/path.js +2 -0
  44. package/dist/lifecycle-BwZ7c9hb.js +596 -0
  45. package/dist/loader.d.ts +5 -6
  46. package/dist/loader.js +3 -2
  47. package/dist/mcp-resources-BREFCmtn.js +39 -0
  48. package/dist/memory-BbwOqDXl.js +248 -0
  49. package/dist/metadata-target-DZEZQGHA.js +1588 -0
  50. package/dist/mountx.d.ts +4 -6
  51. package/dist/mountx.js +10 -8
  52. package/dist/nitro.d.ts +1 -1
  53. package/dist/nitro.js +1 -1
  54. package/dist/nuxt.d.ts +13 -12
  55. package/dist/nuxt.js +10 -8
  56. package/dist/operations-BcpWr41m.js +159 -0
  57. package/dist/operations-CGqY1XeG.js +965 -0
  58. package/dist/operations-DnOwKsJT.d.ts +136 -0
  59. package/dist/operations.d.ts +53 -0
  60. package/dist/operations.js +2 -0
  61. package/dist/{path-CNI6wKIU.js → path-CNAwN7pw.js} +34 -35
  62. package/dist/path-DrSIenjj.js +59 -0
  63. package/dist/path-zHxQUbqa.d.ts +9 -0
  64. package/dist/plugins-DqQ8b4T5.d.ts +10 -0
  65. package/dist/provider-kXjfli9u.js +1457 -0
  66. package/dist/providers/github/store.d.ts +3 -5
  67. package/dist/providers/github/store.js +1 -1
  68. package/dist/registry-Bp-8UUfG.js +129 -0
  69. package/dist/{registry-BIQVCBWI.d.ts → registry-Cg1TJVVZ.d.ts} +3 -4
  70. package/dist/{request-execution-u9mgUXKX.js → request-execution-Dk9rY-Yh.js} +24 -20
  71. package/dist/rolldown-runtime-B4iAMlE-.js +35 -0
  72. package/dist/runtime/assets.d.ts +3 -5
  73. package/dist/runtime/assets.js +9 -6
  74. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  75. package/dist/runtime/empty-registry.d.ts +1 -2
  76. package/dist/runtime/state.d.ts +4 -4
  77. package/dist/runtime/state.js +10 -7
  78. package/dist/runtime/workspace.d.ts +1 -1
  79. package/dist/runtime/workspace.js +1 -1
  80. package/dist/runtime.d.ts +84 -15
  81. package/dist/runtime.js +561 -108
  82. package/dist/{search-C4REyHj9.js → search-CrTmXj5h.js} +10 -9
  83. package/dist/server-BNQ-Nbjj.js +290 -0
  84. package/dist/server.d.ts +22 -34
  85. package/dist/server.js +2 -355
  86. package/dist/shared-DalXdP0i.js +2158 -0
  87. package/dist/source-metadata.d.ts +7 -1
  88. package/dist/source-metadata.js +34 -2
  89. package/dist/{state-TTqa3x3Y.d.ts → state-B8zbLi5t.d.ts} +14 -13
  90. package/dist/store-CXgmu-uw.js +1729 -0
  91. package/dist/{sync-DiuDmSGk.js → sync-CN6ec-5M.js} +62 -41
  92. package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +125 -0
  93. package/dist/test.d.ts +1 -1
  94. package/dist/test.js +1 -1
  95. package/dist/token-CO62GglH.js +61 -0
  96. package/dist/{types-60Yn149G.d.ts → types-DeK9GIxy.d.ts} +348 -49
  97. package/dist/{use-CsV3oIxH.js → use-BQj7nSz6.js} +200 -45
  98. package/dist/{use-CUFSnFCS.d.ts → use-DhwhbAVV.d.ts} +34 -12
  99. package/dist/utils-Blrh4N2n.js +545 -0
  100. package/dist/vite-BEvgU2GY.js +20909 -0
  101. package/dist/vite-CcZmMQ7S.d.ts +476 -0
  102. package/dist/vite.d.ts +2 -50
  103. package/dist/vite.js +2 -2
  104. package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +1565 -0
  105. package/dist/workspace-6pxkOuxr.js +1286 -0
  106. package/dist/workspace-BWJQBK1u.d.ts +7 -0
  107. package/package.json +90 -59
  108. package/dist/chunk-8H4AJuhK.js +0 -14
  109. package/dist/collections/client.d.ts +0 -39
  110. package/dist/collections/client.js +0 -137
  111. package/dist/collections.d.ts +0 -59
  112. package/dist/collections.js +0 -159
  113. package/dist/config-CDoyls2X.js +0 -30
  114. package/dist/config-CZLO0m9h.js +0 -7811
  115. package/dist/file-CHfsZpso.js +0 -23
  116. package/dist/glob-D0vD_wRY.js +0 -17
  117. package/dist/host-CAnbugpI.js +0 -370
  118. package/dist/hosted-vercel-blob-CWBILDVo.js +0 -257
  119. package/dist/lifecycle-BYoa9hVb.js +0 -176
  120. package/dist/provider-C3_elpEh.js +0 -599
  121. package/dist/publish.d.ts +0 -35
  122. package/dist/publish.js +0 -112
  123. package/dist/registry-CqyDTW9Y.js +0 -74
  124. package/dist/runtime-options-BsPSv5O7.js +0 -13
  125. package/dist/shared-jfogBrd5.js +0 -273
  126. package/dist/store-Bs1SLh55.js +0 -414
  127. package/dist/vite-tbfDxtlu.js +0 -2191
  128. package/dist/workspace-66SKyiec.d.ts +0 -6
  129. package/dist/workspace-C4k92Ow8.js +0 -1460
@@ -0,0 +1,1729 @@
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";
8
+ import { posix } from "node:path";
9
+ import { randomUUID } from "node:crypto";
10
+ import { lookup } from "mrmime";
11
+ import * as v from "valibot";
12
+ //#region src/storage/materialization.ts
13
+ const workspaceRevisionMaterializer = Symbol.for("vitehub.workspace.revisionMaterializer");
14
+ function forwardWorkspaceRevisionMaterializer(source, target) {
15
+ const materializer = source[workspaceRevisionMaterializer];
16
+ if (materializer) target[workspaceRevisionMaterializer] = materializer;
17
+ }
18
+ function resolveWorkspaceRevisionMaterializer(workspace) {
19
+ return workspace[workspaceRevisionMaterializer];
20
+ }
21
+ //#endregion
22
+ //#region src/providers/github/publish-reservation.ts
23
+ const githubPublishReservationMs = 3e5;
24
+ const zeroOid = "0".repeat(40);
25
+ const leaseSchema = v.object({
26
+ vitehubPublishReservation: v.literal(1),
27
+ owner: v.string(),
28
+ expiresAt: v.number(),
29
+ head: v.string(),
30
+ opening: v.optional(v.string())
31
+ });
32
+ const commitSchema = v.object({
33
+ message: v.string(),
34
+ tree: v.object({ sha: v.string() }),
35
+ committer: v.optional(v.object({ date: v.string() }))
36
+ });
37
+ /** Expiring preparation claims become durable before dispatching a mutation whose outcome might be ambiguous. */
38
+ async function acquireGitHubPublishReservation(repository, options) {
39
+ const busy = () => workspaceConflict(`[vitehub] A publish is already opening a pull request for ${options.path}. Retry after it finishes or its reservation expires.`, { details: {
40
+ ref: "pull-request",
41
+ path: options.path
42
+ } });
43
+ const expiresAt = Date.now() + githubPublishReservationMs;
44
+ const route = (repo) => `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
45
+ const readCommit = (sha) => githubRequest(repository, async (provider, repo) => v.parse(commitSchema, (await provider.request("GET", `${route(repo)}/git/commits/${encodeURIComponent(sha)}`)).data));
46
+ const base = await readCommit(options.head);
47
+ const owner = randomUUID();
48
+ const writeClaim = (opening) => githubRequest(repository, async (provider, repo) => v.parse(v.object({ sha: v.string() }), (await provider.request("POST", `${route(repo)}/git/commits`, { body: {
49
+ message: JSON.stringify({
50
+ vitehubPublishReservation: 1,
51
+ owner,
52
+ expiresAt,
53
+ head: options.head,
54
+ ...opening ? { opening } : {}
55
+ }),
56
+ parents: [options.head],
57
+ tree: base.tree.sha
58
+ } })).data).sha);
59
+ let owned = await writeClaim();
60
+ async function graphql(query, operationName, variables) {
61
+ return githubRequest(repository, async (provider) => {
62
+ const response = v.parse(v.object({
63
+ data: v.optional(v.unknown()),
64
+ errors: v.optional(v.array(v.object({ message: v.string() })))
65
+ }), (await provider.request("POST", "/graphql", { body: {
66
+ query,
67
+ operationName,
68
+ variables
69
+ } })).data);
70
+ if (response.errors?.length) throw workspaceError(`[vitehub] GitHub publish reservation failed: ${response.errors.map((error) => error.message).join("; ")}`);
71
+ return response.data;
72
+ });
73
+ }
74
+ async function replace(expected, next) {
75
+ const repo = await githubRequest(repository, async (_provider, repo) => repo);
76
+ const { repository: { id } } = v.parse(v.object({ repository: v.object({ id: v.string() }) }), await graphql("query RepositoryId($owner:String!,$name:String!){repository(owner:$owner,name:$name){id}}", "RepositoryId", {
77
+ owner: repo.owner,
78
+ name: repo.name
79
+ }));
80
+ try {
81
+ v.parse(v.object({ updateRefs: v.object({ clientMutationId: v.nullable(v.string()) }) }), await graphql("mutation UpdateRefs($input:UpdateRefsInput!){updateRefs(input:$input){clientMutationId}}", "UpdateRefs", { input: {
82
+ repositoryId: id,
83
+ refUpdates: [{
84
+ name: `refs/heads/${options.branch}`,
85
+ beforeOid: expected,
86
+ afterOid: next,
87
+ force: true
88
+ }]
89
+ } }));
90
+ return true;
91
+ } catch (error) {
92
+ const current = await readCurrentHead(repository, options.branch);
93
+ if (current === next) return true;
94
+ if (current !== expected) return false;
95
+ throw error;
96
+ }
97
+ }
98
+ try {
99
+ await githubRequest(repository, async (provider, repo) => await provider.request("POST", `${route(repo)}/git/refs`, { body: {
100
+ ref: `refs/heads/${options.branch}`,
101
+ sha: owned
102
+ } }));
103
+ } catch (error) {
104
+ if (githubRequestStatus(error) !== 422) throw error;
105
+ const current = await readCurrentHead(repository, options.branch);
106
+ if (!current) throw error;
107
+ const commit = await readCommit(current);
108
+ let expiry;
109
+ let opening;
110
+ try {
111
+ const lease = v.parse(leaseSchema, JSON.parse(commit.message));
112
+ expiry = lease.expiresAt;
113
+ opening = lease.opening;
114
+ } catch {
115
+ expiry = Date.parse(commit.committer?.date ?? "") + githubPublishReservationMs;
116
+ }
117
+ if (!Number.isFinite(expiry) || expiry > Date.now()) throw busy();
118
+ if (opening) {
119
+ if (!await githubRequest(repository, async (provider, repo) => {
120
+ const query = new URLSearchParams({
121
+ state: "all",
122
+ head: `${repo.owner}:${opening}`,
123
+ per_page: "1"
124
+ });
125
+ return v.parse(v.array(v.object({ head: v.object({ ref: v.string() }) })), (await provider.request("GET", `${route(repo)}/pulls?${query}`)).data).some((request) => request.head.ref === opening);
126
+ })) throw workspaceConflict(`[vitehub] GitHub has not confirmed the publish pull request from ${opening} for ${options.path}. Keep its branch and reservation; retry after GitHub reports the result.`, { details: {
127
+ ref: "pull-request",
128
+ path: options.path,
129
+ head: opening
130
+ } });
131
+ }
132
+ if (!await replace(current, owned)) throw busy();
133
+ }
134
+ async function assertOwned() {
135
+ if (await readCurrentHead(repository, options.branch) !== owned || Date.now() >= expiresAt) throw busy();
136
+ }
137
+ return {
138
+ expiresAt,
139
+ assertOwned,
140
+ async begin(opening) {
141
+ await assertOwned();
142
+ const previous = owned;
143
+ owned = await writeClaim(opening);
144
+ if (!await replace(previous, owned)) throw busy();
145
+ },
146
+ async release() {
147
+ await replace(owned, zeroOid);
148
+ }
149
+ };
150
+ }
151
+ //#endregion
152
+ //#region src/providers/github/history.ts
153
+ /**
154
+ * How long `head()` keeps the head that it read for a branch, in milliseconds. A commit through this history replaces
155
+ * the head at once. A commit by another writer shows after this time at most.
156
+ */
157
+ const githubHeadCacheMs = 5e3;
158
+ const metadataTrailer = "Vitehub-Metadata: ";
159
+ const metadataTrailerPattern = /(?:^|\n\n)Vitehub-Metadata: ([^\n]*)\s*$/;
160
+ const reservedTrailerPattern = /^Vitehub-Metadata:/m;
161
+ /** The most bytes of commit metadata as JSON, and of a commit message, that the Store writes. */
162
+ const githubMaxMetadataBytes = 65536;
163
+ const githubMaxMessageBytes = 16384;
164
+ function nonEmptyString(value) {
165
+ return typeof value === "string" && value.length > 0;
166
+ }
167
+ function malformed(description) {
168
+ throw workspaceError(`[vitehub] GitHub workspace returned a malformed ${description} response.`);
169
+ }
170
+ function isNoHistoryError(error) {
171
+ const status = githubRequestStatus(error);
172
+ return status === 404 || status === 409;
173
+ }
174
+ function cursorFor(ref, id) {
175
+ return `${ref}:after:${id}`;
176
+ }
177
+ function pageFromCursor(ref, cursor) {
178
+ if (!cursor) return 1;
179
+ const separator = cursor.lastIndexOf(":");
180
+ const cursorRef = separator < 0 ? "" : cursor.slice(0, separator);
181
+ const page = separator < 0 ? NaN : Number(cursor.slice(separator + 1));
182
+ if (cursorRef !== ref || !Number.isSafeInteger(page) || page < 1) throw workspaceErrorDiagnostics.WORKSPACE_R0070({ message: `[vitehub] History cursor does not belong to ref "${ref}".` });
183
+ return page;
184
+ }
185
+ /** The page number of the next GitHub page, from the Forge cursor. */
186
+ function nextPage(nextUrl) {
187
+ if (!nextUrl) return void 0;
188
+ const page = Number(new URL(nextUrl).searchParams.get("page"));
189
+ return Number.isSafeInteger(page) && page > 1 ? page : void 0;
190
+ }
191
+ function visibleWorkspacePath(path) {
192
+ const parts = path.split("/");
193
+ return !parts.some((part) => part.toLowerCase() === ".git") && parts[0]?.toLowerCase() !== ".vitehub";
194
+ }
195
+ function entryMetadata(entry) {
196
+ return entry.mode === "100644" ? void 0 : { gitMode: entry.mode };
197
+ }
198
+ function mediaType(path) {
199
+ return lookup(path) || "application/octet-stream";
200
+ }
201
+ /** The message of a commit without its metadata trailer, and the metadata that the trailer holds. */
202
+ function readCommitMessage(message) {
203
+ if (!message) return {};
204
+ const match = metadataTrailerPattern.exec(message);
205
+ if (!match) return { message };
206
+ if (new TextEncoder().encode(match[1]).byteLength > 65536) return { message };
207
+ let metadata;
208
+ try {
209
+ const value = JSON.parse(match[1]);
210
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) metadata = Object.fromEntries(Object.entries(value));
211
+ } catch {
212
+ return { message };
213
+ }
214
+ if (!metadata) return { message };
215
+ const text = message.slice(0, match.index).trimEnd();
216
+ return {
217
+ ...text ? { message: text } : {},
218
+ metadata
219
+ };
220
+ }
221
+ function messageWithMetadata(message, metadata) {
222
+ const limit = (what, size, max) => {
223
+ if (size > max) throw workspaceErrorDiagnostics.WORKSPACE_R0073({ message: `[vitehub] GitHub history commit ${what} is ${size} bytes, over the limit of ${max}. Shorten it.` });
224
+ };
225
+ if (reservedTrailerPattern.test(message)) throw workspaceErrorDiagnostics.WORKSPACE_R0073({ message: `[vitehub] GitHub history commit message cannot contain a line that starts with "${metadataTrailer.trim()}". The Store writes that line from the metadata option. Remove it.` });
226
+ limit("message", new TextEncoder().encode(message).byteLength, githubMaxMessageBytes);
227
+ if (!metadata || !Object.keys(metadata).length) return message;
228
+ const json = JSON.stringify(metadata);
229
+ limit("metadata", new TextEncoder().encode(json).byteLength, githubMaxMetadataBytes);
230
+ return `${message}\n\n${metadataTrailer}${json}`;
231
+ }
232
+ function publicRevision(commit, ref, entries, url, suppliedMetadata) {
233
+ const stored = readCommitMessage(commit.message);
234
+ suppliedMetadata ??= stored.metadata;
235
+ const author = commit.author;
236
+ const committer = commit.committer;
237
+ const authorName = author?.name || committer?.name;
238
+ const authorEmail = author?.email || committer?.email;
239
+ const authorLogin = author?.actor?.login || committer?.actor?.login;
240
+ const authorMetadata = authorName || authorEmail || authorLogin ? {
241
+ ...authorName ? { author: authorName } : {},
242
+ ...authorEmail ? { authorEmail } : {},
243
+ ...authorLogin ? { authorLogin } : {}
244
+ } : {};
245
+ const metadata = Object.keys(authorMetadata).length || commit.url || url || suppliedMetadata ? {
246
+ ...suppliedMetadata,
247
+ ...authorMetadata,
248
+ ...commit.url || url ? { url: commit.url || url } : {}
249
+ } : void 0;
250
+ const createdAt = author?.date || committer?.date;
251
+ if (!createdAt || Number.isNaN(createdAt.getTime())) malformed("commit");
252
+ return {
253
+ id: commit.sha,
254
+ ref,
255
+ parentId: commit.parents[0] || null,
256
+ createdAt: createdAt.toISOString(),
257
+ ...stored.message ? { message: stored.message } : {},
258
+ ...metadata ? { metadata } : {},
259
+ files: entries.length,
260
+ bytes: entries.reduce((total, entry) => total + entry.size, 0)
261
+ };
262
+ }
263
+ function viewPath(path) {
264
+ return normalizeSafeWorkspacePath(path, { allowEmpty: true }).split("/").filter(Boolean).join("/");
265
+ }
266
+ function asHistoryEntry(entry, root) {
267
+ if (entry.type !== "file" && entry.type !== "symlink") return void 0;
268
+ if (!entry.sha) malformed("tree");
269
+ const path = entry.path.startsWith(`${root}/`) ? entry.path.slice(root.length + 1) : root ? void 0 : entry.path;
270
+ if (path === void 0 || !path || !visibleWorkspacePath(path)) return void 0;
271
+ return {
272
+ mode: gitFileMode(entry.mode),
273
+ path,
274
+ sha: entry.sha,
275
+ size: entry.size || 0
276
+ };
277
+ }
278
+ function isHistoryFileInput(file) {
279
+ return typeof file.content === "string" || ArrayBuffer.isView(file.content);
280
+ }
281
+ function isSupportedHistoryRef(name) {
282
+ try {
283
+ normalizeHistoryRef(name);
284
+ return true;
285
+ } catch {
286
+ return false;
287
+ }
288
+ }
289
+ /** A read-through view of GitHub branches and commits using the retained Workspace history contract. */
290
+ function createGitHubWorkspaceHistory(input) {
291
+ let resolved;
292
+ const settings = () => resolved ??= typeof input === "function" ? input() : input;
293
+ const options = {
294
+ get branch() {
295
+ return settings().branch;
296
+ },
297
+ get refs() {
298
+ return settings().refs;
299
+ },
300
+ get repository() {
301
+ return settings().repository;
302
+ },
303
+ get root() {
304
+ return settings().root;
305
+ }
306
+ };
307
+ const client = () => settings().client;
308
+ const toBranch = (ref) => {
309
+ const refs = options.refs;
310
+ return (ref === "published" ? refs?.published : ref === "draft" ? refs?.draft : void 0) ?? ref;
311
+ };
312
+ /**
313
+ * A given ref name, its branch, and the name that revisions on it report. The branch of an alias is reached only by
314
+ * the alias, so a caller cannot write the published branch under another name and skip the rules that guard `published`.
315
+ * A call without `ref` uses `main`, which is the alias when `refs` points `published` at it.
316
+ */
317
+ const resolveRef = (given) => {
318
+ const name = normalizeHistoryRef(given);
319
+ const refs = options.refs;
320
+ if (given !== void 0 && name !== "published" && name !== "draft" && (name === refs?.published || name === refs?.draft)) {
321
+ const alias = name === refs?.published ? "published" : "draft";
322
+ throw workspaceErrorDiagnostics.WORKSPACE_R0071({ message: `[vitehub] History ref ${JSON.stringify(name)} is the branch of the ref ${JSON.stringify(alias)} in this Store. Use ${JSON.stringify(alias)}.` });
323
+ }
324
+ const branch = toBranch(name);
325
+ return {
326
+ branch,
327
+ ref: fromBranch(branch)
328
+ };
329
+ };
330
+ const fromBranch = (branch) => {
331
+ const refs = options.refs;
332
+ if (refs?.published === branch) return "published";
333
+ if (refs?.draft === branch) return "draft";
334
+ return branch;
335
+ };
336
+ const hiddenBranch = (branch) => toBranch(fromBranch(branch)) !== branch;
337
+ const heads = /* @__PURE__ */ new Map();
338
+ const commitCache = /* @__PURE__ */ new Map();
339
+ const treeCache = /* @__PURE__ */ new Map();
340
+ const commitRefs = /* @__PURE__ */ new Map();
341
+ const readCommit = async (id) => {
342
+ const cached = commitCache.get(id);
343
+ if (cached) return cached;
344
+ const commit = await githubRequest(client(), async (provider, repo) => await provider.commits.get({
345
+ forge: provider.forge,
346
+ instance: provider.instance,
347
+ repo,
348
+ sha: encodeURIComponent(id)
349
+ }), "commit");
350
+ if (!nonEmptyString(commit.sha)) malformed("commit");
351
+ commitCache.set(commit.sha, commit);
352
+ return commit;
353
+ };
354
+ const readTreeItems = async (ref, recursive) => await githubRequest(client(), async (provider, repo) => {
355
+ const tree = provider.contents.tree(repo, {
356
+ recursive,
357
+ ref
358
+ });
359
+ const items = [];
360
+ for await (const item of tree) items.push(item);
361
+ return {
362
+ items,
363
+ truncated: tree.warnings.some((warning) => warning.code === "tree_truncated")
364
+ };
365
+ }, "tree");
366
+ const readTree = async (commit) => {
367
+ const cached = treeCache.get(commit.sha);
368
+ if (cached) return cached;
369
+ const tree = await readTreeItems(commit.sha, true);
370
+ const entries = (tree.truncated ? await readTreeWithoutRecursion(commit.sha) : tree.items).flatMap((entry) => {
371
+ const historyEntry = asHistoryEntry(entry, options.root);
372
+ return historyEntry ? [historyEntry] : [];
373
+ }).sort((left, right) => left.path.localeCompare(right.path));
374
+ treeCache.set(commit.sha, entries);
375
+ return entries;
376
+ };
377
+ const readTreeWithoutRecursion = async (ref) => {
378
+ const root = options.root.replace(/^\/+|\/+$/g, "");
379
+ const entries = [];
380
+ const walk = async (sha, prefix) => {
381
+ const tree = await readTreeItems(sha, false);
382
+ if (tree.truncated) throw workspaceError("[vitehub] GitHub workspace tree was truncated while traversing a directory.");
383
+ for (const entry of tree.items) {
384
+ const path = prefix ? `${prefix}/${entry.path}` : entry.path;
385
+ if (!(!root || path === root || path.startsWith(`${root}/`) || root.startsWith(`${path}/`))) continue;
386
+ if (entry.type === "directory") {
387
+ if (!entry.sha) malformed("tree");
388
+ await walk(entry.sha, path);
389
+ } else entries.push({
390
+ ...entry,
391
+ path
392
+ });
393
+ }
394
+ };
395
+ await walk(ref, "");
396
+ return entries;
397
+ };
398
+ const revision = async (ref, id, suppliedMetadata) => {
399
+ const commit = await readCommit(id);
400
+ const entries = await readTree(commit);
401
+ commitRefs.set(commit.sha, ref);
402
+ return publicRevision(commit, ref, entries, `https://github.com/${options.repository}/commit/${commit.sha}`, suppliedMetadata);
403
+ };
404
+ const readBranches = async () => {
405
+ try {
406
+ return await githubRequest(client(), async (provider, repo) => {
407
+ const branches = [];
408
+ for await (const branch of provider.contents.branches(repo, { perPage: 100 })) {
409
+ if (!nonEmptyString(branch.name) || !nonEmptyString(branch.sha)) malformed("branch list");
410
+ if (isSupportedHistoryRef(branch.name) && !hiddenBranch(branch.name)) branches.push({
411
+ commit: branch.sha,
412
+ name: branch.name
413
+ });
414
+ }
415
+ return branches;
416
+ }, "branch list");
417
+ } catch (error) {
418
+ if (isNoHistoryError(error)) return [];
419
+ throw error;
420
+ }
421
+ };
422
+ const readBranchHead = async (branch) => {
423
+ const cached = heads.get(branch);
424
+ if (cached && cached.expires > Date.now()) return await cached.head;
425
+ const head = (async () => {
426
+ try {
427
+ return await githubRequest(client(), async (provider, repo) => await provider.contents.resolveRef(repo, `heads/${branch}`), "commit");
428
+ } catch (error) {
429
+ if (isNoHistoryError(error) || githubRequestStatus(error) === 422) return null;
430
+ throw error;
431
+ }
432
+ })();
433
+ heads.set(branch, {
434
+ expires: Date.now() + githubHeadCacheMs,
435
+ head
436
+ });
437
+ head.catch(() => {
438
+ if (heads.get(branch)?.head === head) heads.delete(branch);
439
+ });
440
+ return await head;
441
+ };
442
+ const list = async (listOptions = {}) => {
443
+ const { branch, ref } = resolveRef(listOptions.ref);
444
+ const limit = listOptions.limit ?? 20;
445
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw workspaceErrorDiagnostics.WORKSPACE_R0070({ message: "[vitehub] History list limit must be an integer from 1 to 100." });
446
+ const separator = listOptions.cursor?.lastIndexOf(":after:") ?? -1;
447
+ const revisionCursor = separator < 0 ? void 0 : listOptions.cursor.slice(separator + 7);
448
+ 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
+ const afterId = revisionCursor ?? (listOptions.cursor && /^[0-9a-f]{40}$/i.test(listOptions.cursor) ? listOptions.cursor : void 0);
450
+ const page = afterId ? 1 : pageFromCursor(ref, listOptions.cursor);
451
+ const gitPath = !listOptions.path ? "" : joinGitPath(options.root, normalizeHistoryPath(listOptions.path));
452
+ let result;
453
+ try {
454
+ result = await githubRequest(client(), async (provider, repo) => {
455
+ const cursor = page === 1 ? void 0 : { nextUrl: `${provider.baseUrl.replace(/\/+$/, "")}/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}/commits?sha=${encodeURIComponent(branch)}&per_page=${limit}&page=${page}${gitPath ? `&path=${encodeURIComponent(gitPath)}` : ""}` };
456
+ return await provider.commits.list(repo, {
457
+ cursor,
458
+ perPage: afterId ? Math.min(limit + 1, 100) : limit,
459
+ ref: afterId ?? branch,
460
+ ...gitPath ? { path: gitPath } : {}
461
+ }).page();
462
+ }, "commit list");
463
+ } catch (error) {
464
+ if (isNoHistoryError(error)) return { revisions: [] };
465
+ throw error;
466
+ }
467
+ const items = afterId && result.items[0]?.sha === afterId ? result.items.slice(1) : result.items;
468
+ 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
+ }));
473
+ const followingPage = nextPage(result.cursor?.nextUrl);
474
+ if (afterId) {
475
+ const last = shown.at(-1)?.sha;
476
+ return {
477
+ revisions,
478
+ ...last && (items.length > limit || followingPage !== void 0) ? { cursor: cursorFor(ref, last) } : {}
479
+ };
480
+ }
481
+ const last = shown.at(-1)?.sha;
482
+ return {
483
+ revisions,
484
+ ...last && followingPage !== void 0 ? { cursor: cursorFor(ref, last) } : {}
485
+ };
486
+ };
487
+ const refs = async () => {
488
+ const branches = await readBranches();
489
+ return (await Promise.all(branches.map(async (branch) => ({
490
+ name: fromBranch(branch.name),
491
+ head: await revision(fromBranch(branch.name), branch.commit)
492
+ })))).sort((left, right) => left.name.localeCompare(right.name));
493
+ };
494
+ const refForCommit = async (id) => {
495
+ const cached = commitRefs.get(id);
496
+ if (cached) return cached;
497
+ const branches = await readBranches();
498
+ const heads = branches.filter((branch) => branch.commit === id);
499
+ let branch = heads.find((branch) => branch.name === options.branch) ?? heads[0];
500
+ if (!branch) {
501
+ const ordered = [...branches].sort((left, right) => Number(right.name === options.branch) - Number(left.name === options.branch));
502
+ 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")) {
509
+ branch = candidate;
510
+ break;
511
+ }
512
+ }
513
+ const ref = fromBranch(branch?.name ?? options.branch);
514
+ commitRefs.set(id, ref);
515
+ return ref;
516
+ };
517
+ const open = async (id) => {
518
+ if (!nonEmptyString(id)) throw workspaceError("[vitehub] Workspace revision id must be a non-empty string.");
519
+ let commit;
520
+ try {
521
+ commit = await readCommit(id);
522
+ } catch (error) {
523
+ const status = githubRequestStatus(error);
524
+ if (status === 404 || status === 422) throw workspaceError(`[vitehub] Workspace revision does not exist: ${id}.`);
525
+ throw error;
526
+ }
527
+ const ref = await refForCommit(commit.sha);
528
+ const entries = await readTree(commit);
529
+ const byPath = new Map(entries.map((entry) => [entry.path, entry]));
530
+ const directories = /* @__PURE__ */ new Map();
531
+ directories.set("", {
532
+ path: "",
533
+ type: "directory"
534
+ });
535
+ for (const entry of entries) {
536
+ const parts = entry.path.split("/");
537
+ for (let index = 1; index < parts.length; index++) {
538
+ const path = parts.slice(0, index).join("/");
539
+ directories.set(path, {
540
+ path,
541
+ type: "directory"
542
+ });
543
+ }
544
+ }
545
+ const revisionValue = publicRevision(commit, ref, entries, `https://github.com/${options.repository}/commit/${commit.sha}`);
546
+ return Object.freeze({
547
+ revision: revisionValue,
548
+ list: async (path = "", listOptions) => {
549
+ const prefix = viewPath(path);
550
+ return [...directories.values(), ...entries.map((entry) => ({
551
+ path: entry.path,
552
+ type: "file",
553
+ size: entry.size,
554
+ mediaType: mediaType(entry.path),
555
+ digest: entry.sha,
556
+ ...entryMetadata(entry) ? { metadata: entryMetadata(entry) } : {}
557
+ }))].filter((entry) => entry.path && entry.path !== prefix && (!prefix || entry.path.startsWith(`${prefix}/`)) && !isExcludedWorkspacePath(entry.path, listOptions?.exclude) && (listOptions?.recursive || !entry.path.slice(prefix ? prefix.length + 1 : 0).includes("/"))).sort((left, right) => left.path.localeCompare(right.path));
558
+ },
559
+ stat: async (path) => {
560
+ const normalized = viewPath(path);
561
+ const directory = directories.get(normalized);
562
+ if (directory) return { ...directory };
563
+ const entry = byPath.get(normalized);
564
+ if (!entry) throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
565
+ return {
566
+ path: normalized,
567
+ type: "file",
568
+ revision: commit.sha,
569
+ size: entry.size,
570
+ mediaType: mediaType(normalized),
571
+ digest: entry.sha,
572
+ ...entryMetadata(entry) ? { metadata: entryMetadata(entry) } : {}
573
+ };
574
+ },
575
+ readFile: async (path, readOptions) => {
576
+ const normalized = normalizeHistoryPath(path);
577
+ const entry = byPath.get(normalized);
578
+ if (!entry) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
579
+ const bytes = await readGitHubFile(client(), {
580
+ ...entry,
581
+ path: joinGitPath(options.root, normalized)
582
+ }, commit.sha);
583
+ return decodeFile(bytes, readOptions);
584
+ }
585
+ });
586
+ };
587
+ const usage = async () => {
588
+ const branches = await readBranches();
589
+ const seen = /* @__PURE__ */ new Set();
590
+ let bytes = 0;
591
+ for (const branch of branches) {
592
+ let cursor;
593
+ do {
594
+ const page = await list({
595
+ ref: fromBranch(branch.name),
596
+ cursor,
597
+ limit: 100
598
+ });
599
+ for (const revisionValue of page.revisions) {
600
+ const entries = await readTree(await readCommit(revisionValue.id));
601
+ for (const entry of entries) {
602
+ if (seen.has(entry.sha)) continue;
603
+ seen.add(entry.sha);
604
+ bytes += entry.size;
605
+ }
606
+ }
607
+ cursor = page.cursor;
608
+ } while (cursor);
609
+ }
610
+ return {
611
+ bytes,
612
+ objects: seen.size
613
+ };
614
+ };
615
+ const commit = async (commitOptions) => {
616
+ const { branch, ref } = resolveRef(commitOptions.ref);
617
+ if (commitOptions.ifHead !== null && !nonEmptyString(commitOptions.ifHead)) throw workspaceError("[vitehub] History commit requires ifHead to be a revision id or null.");
618
+ const publishedBranch = options.refs?.published;
619
+ const state = await readGitHubBranchState({
620
+ branch,
621
+ fork: publishedBranch && publishedBranch !== branch ? publishedBranch : void 0,
622
+ from: commitOptions.startFrom,
623
+ repository: client(),
624
+ root: options.root
625
+ });
626
+ const actual = state.branchExists ? state.refSha : null;
627
+ if (actual !== commitOptions.ifHead) {
628
+ heads.delete(branch);
629
+ throw historyConflict(ref, commitOptions.ifHead, actual);
630
+ }
631
+ for (const [expectedRef, expectedHead] of Object.entries(commitOptions.ifHeads ?? {})) {
632
+ const expected = resolveRef(expectedRef);
633
+ const currentHead = await readCurrentHead(client(), expected.branch);
634
+ if (currentHead !== expectedHead) {
635
+ heads.delete(expected.branch);
636
+ throw historyConflict(expected.ref, expectedHead, currentHead);
637
+ }
638
+ }
639
+ const updates = [];
640
+ const deletes = [];
641
+ const desired = /* @__PURE__ */ new Map();
642
+ if (commitOptions.files !== void 0) {
643
+ for (const [path, file] of Object.entries(commitOptions.files)) desired.set(normalizeHistoryPath(path), file);
644
+ for (const [path] of state.files) if (visibleWorkspacePath(path) && !desired.has(path)) deletes.push(joinGitPath(options.root, path));
645
+ } else {
646
+ for (const [path, file] of Object.entries(commitOptions.changes?.put || {})) desired.set(normalizeHistoryPath(path), file);
647
+ for (const path of commitOptions.changes?.delete || []) {
648
+ const normalized = normalizeHistoryPath(path);
649
+ if (!state.files.has(normalized)) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
650
+ deletes.push(joinGitPath(options.root, normalized));
651
+ }
652
+ }
653
+ for (const [path, file] of desired) {
654
+ if (!isHistoryFileInput(file)) throw workspaceError(`[vitehub] Invalid history file content: ${path}.`);
655
+ const bytes = new Uint8Array(contentToBytes(file.content));
656
+ const current = state.files.get(path);
657
+ const mode = file.metadata?.gitMode === "120000" || file.metadata?.gitMode === "100755" || file.metadata?.gitMode === "100644" ? file.metadata.gitMode : current?.mode ?? "100644";
658
+ if (current?.sha === await gitBlobSha(bytes) && current.mode === mode) continue;
659
+ updates.push({
660
+ bytes,
661
+ fullPath: joinGitPath(options.root, path),
662
+ mode
663
+ });
664
+ }
665
+ if (!updates.length && !deletes.length) {
666
+ if (!state.branchExists) throw workspaceError(`[vitehub] GitHub history commit cannot create ref "${ref}" without a file change.`);
667
+ if (commitOptions.metadata === void 0) return await revision(ref, state.refSha);
668
+ }
669
+ const commitSha = await commitGitHubChanges({
670
+ branch,
671
+ branchExists: state.branchExists,
672
+ deletePaths: deletes,
673
+ files: updates,
674
+ message: messageWithMetadata(commitOptions.message || "Update Workspace", commitOptions.metadata),
675
+ parentSha: state.refSha,
676
+ remoteModes: new Map([...state.files.values()].map((entry) => [entry.path, entry.mode])),
677
+ repository: client()
678
+ });
679
+ heads.set(branch, {
680
+ expires: Date.now() + githubHeadCacheMs,
681
+ head: Promise.resolve(commitSha)
682
+ });
683
+ return await revision(ref, commitSha, commitOptions.metadata);
684
+ };
685
+ let pullRequestCache;
686
+ const repoPath = (repo) => `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
687
+ const refPath = (branch) => branch.split("/").map(encodeURIComponent).join("/");
688
+ /** Matching refs are returned as one complete array; this endpoint does not support page parameters. */
689
+ const matchingBranches = async (prefix) => await githubRequest(client(), async (provider, repo) => {
690
+ const response = await provider.request("GET", `${repoPath(repo)}/git/matching-refs/heads/${refPath(prefix)}`);
691
+ const names = /* @__PURE__ */ new Set();
692
+ for (const item of Array.isArray(response.data) ? response.data : []) {
693
+ const name = item !== null && typeof item === "object" ? Reflect.get(item, "ref") : void 0;
694
+ if (nonEmptyString(name) && name.startsWith("refs/heads/")) names.add(name.slice(11));
695
+ }
696
+ return [...names];
697
+ }, "branch list");
698
+ /** The open pull request whose head is `branch`, found by the head filter of the pulls endpoint. */
699
+ const openPullRequestOf = async (branch) => await githubRequest(client(), async (provider, repo) => {
700
+ const response = await provider.request("GET", `${repoPath(repo)}/pulls`, { query: {
701
+ state: "open",
702
+ head: `${repo.owner}:${branch}`,
703
+ per_page: 5
704
+ } });
705
+ for (const item of Array.isArray(response.data) ? response.data : []) {
706
+ if (item === null || typeof item !== "object") continue;
707
+ const number = Reflect.get(item, "number");
708
+ const url = Reflect.get(item, "html_url");
709
+ const title = Reflect.get(item, "title");
710
+ const base = Reflect.get(Object(Reflect.get(item, "base")), "ref");
711
+ const headRef = Reflect.get(Object(Reflect.get(item, "head")), "ref");
712
+ if (!Number.isSafeInteger(number) || !nonEmptyString(url) || !nonEmptyString(base) || headRef !== branch) continue;
713
+ if (hiddenBranch(base)) continue;
714
+ const baseSha = Reflect.get(Object(Reflect.get(item, "base")), "sha");
715
+ const headSha = Reflect.get(Object(Reflect.get(item, "head")), "sha");
716
+ if (!nonEmptyString(baseSha) || !nonEmptyString(headSha)) malformed("pull request");
717
+ const compare = (await provider.request("GET", `${repoPath(repo)}/compare/${encodeURIComponent(baseSha)}...${encodeURIComponent(headSha)}`)).data;
718
+ const mergeBase = Reflect.get(Object(Reflect.get(Object(compare), "merge_base_commit")), "sha");
719
+ if (!nonEmptyString(mergeBase)) malformed("compare");
720
+ return {
721
+ number: Number(number),
722
+ url,
723
+ title: String(title ?? ""),
724
+ head: fromBranch(branch),
725
+ base: fromBranch(base),
726
+ mergeBase
727
+ };
728
+ }
729
+ }, "pull request list");
730
+ const findPullRequests = async (prefix) => {
731
+ return (await Promise.all((await matchingBranches(prefix)).map(async (branch) => await openPullRequestOf(branch)))).filter((entry) => entry !== void 0).sort((left, right) => right.number - left.number);
732
+ };
733
+ const pullRequests = async (listOptions) => {
734
+ const prefix = listOptions?.headPrefix ?? "";
735
+ if (!prefix) throw workspaceError("[vitehub] pullRequests() requires a headPrefix on the GitHub Store.");
736
+ if (!pullRequestCache || pullRequestCache.expires <= Date.now() || pullRequestCache.prefix !== prefix) {
737
+ const value = findPullRequests(prefix);
738
+ pullRequestCache = {
739
+ expires: Date.now() + githubHeadCacheMs,
740
+ prefix,
741
+ value
742
+ };
743
+ value.catch(() => {
744
+ if (pullRequestCache?.value === value) pullRequestCache = void 0;
745
+ });
746
+ }
747
+ return await pullRequestCache.value;
748
+ };
749
+ const deleteBranch = async (branch) => {
750
+ heads.delete(branch);
751
+ await githubRequest(client(), async (provider, repo) => await provider.request("DELETE", `${repoPath(repo)}/git/refs/heads/${refPath(branch)}`));
752
+ };
753
+ const openPullRequest = async (pullRequest) => {
754
+ const head = resolveRef(pullRequest.head);
755
+ const base = resolveRef(pullRequest.base);
756
+ const locks = [];
757
+ let created;
758
+ let number;
759
+ let dispatched = false;
760
+ let uncertain = false;
761
+ try {
762
+ if (pullRequest.reservation) {
763
+ if (!pullRequest.reservation.headPrefix) throw workspaceError("[vitehub] A pull request reservation requires a headPrefix.");
764
+ const paths = [...new Set(pullRequest.reservation.paths.map(normalizeHistoryPath))].sort();
765
+ const sha = await readCurrentHead(client(), head.branch);
766
+ if (!sha) throw workspaceError(`[vitehub] Pull request branch does not exist: ${head.ref}.`);
767
+ for (const path of paths) {
768
+ const lock = `vitehub/reservations/${await gitBlobSha(new TextEncoder().encode(JSON.stringify([base.branch, joinGitPath(options.root, path)])))}`;
769
+ locks.push(await acquireGitHubPublishReservation(client(), {
770
+ branch: lock,
771
+ head: sha,
772
+ path
773
+ }));
774
+ }
775
+ pullRequestCache = void 0;
776
+ const requests = await findPullRequests(pullRequest.reservation.headPrefix);
777
+ const published = await readCurrentHead(client(), base.branch);
778
+ const main = published ? await readFullTree(published) : /* @__PURE__ */ new Map();
779
+ for (const request of requests) {
780
+ if (request.base !== base.ref || request.head === head.ref || !request.mergeBase) continue;
781
+ const current = await readCurrentHead(client(), resolveRef(request.head).branch);
782
+ if (!current) continue;
783
+ const [branch, parent] = await Promise.all([readFullTree(current), readFullTree(request.mergeBase)]);
784
+ for (const path of paths) {
785
+ const fullPath = joinGitPath(options.root, path);
786
+ const digest = branch.get(fullPath)?.sha;
787
+ if (digest === parent.get(fullPath)?.sha || digest === main.get(fullPath)?.sha) continue;
788
+ throw workspaceConflict(`[vitehub] An open pull request already publishes ${path}: #${request.number} (${request.url}). Merge or close it, then publish again.`, { details: {
789
+ ref: "pull-request",
790
+ path
791
+ } });
792
+ }
793
+ }
794
+ }
795
+ await Promise.all(locks.map((lock) => lock.assertOwned()));
796
+ for (const lock of locks) await lock.begin(head.branch);
797
+ const deadline = locks.length ? Math.min(...locks.map((lock) => lock.expiresAt)) : void 0;
798
+ dispatched = true;
799
+ created = await githubRequest(client(), async (provider, repo) => await provider.threads.create(repo, {
800
+ kind: "pull_request",
801
+ title: pullRequest.title,
802
+ body: pullRequest.body,
803
+ head: head.branch,
804
+ base: base.branch,
805
+ draft: pullRequest.draft
806
+ }, deadline ? { signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())) } : void 0), "pull request");
807
+ number = Number(created.ref.number);
808
+ if (!Number.isSafeInteger(number) || !created.url) malformed("pull request");
809
+ } catch (error) {
810
+ const status = githubRequestStatus(error);
811
+ uncertain = dispatched && !(status !== void 0 && status >= 400 && status < 500 && status !== 408);
812
+ if (!uncertain && pullRequest.deleteHeadOnFailure) await deleteBranch(head.branch).catch(() => void 0);
813
+ throw error;
814
+ } finally {
815
+ if (!uncertain) await Promise.all(locks.map(async (lock) => await lock.release().catch(() => void 0)));
816
+ }
817
+ pullRequestCache = void 0;
818
+ return {
819
+ number,
820
+ url: created.url,
821
+ title: created.title,
822
+ head: head.ref,
823
+ base: base.ref
824
+ };
825
+ };
826
+ /**
827
+ * GitHub answers 409 to a merge that conflicts, and to one that raced another update of the branch. The body of the
828
+ * response tells them apart: "Merge conflict" against "Head branch was modified".
829
+ */
830
+ const isMergeConflict = (error) => {
831
+ if (githubRequestStatus(error) !== 409) return false;
832
+ for (const entry of [error, error instanceof Error ? error.cause : void 0]) {
833
+ const body = entry !== null && typeof entry === "object" ? Reflect.get(entry, "body") : void 0;
834
+ if (typeof body === "string" && /merge conflict/i.test(body)) return true;
835
+ }
836
+ return false;
837
+ };
838
+ /** The files of a commit by repository path, with their blob sha and mode. */
839
+ const readFullTree = async (sha) => await githubRequest(client(), async (provider, repo) => {
840
+ const tree = provider.contents.tree(repo, {
841
+ recursive: true,
842
+ ref: sha
843
+ });
844
+ const files = /* @__PURE__ */ new Map();
845
+ for await (const entry of tree) {
846
+ if (entry.type !== "file" && entry.type !== "symlink") continue;
847
+ if (!entry.sha) malformed("tree");
848
+ files.set(entry.path, {
849
+ mode: gitFileMode(entry.mode),
850
+ sha: entry.sha
851
+ });
852
+ }
853
+ if (tree.warnings.some((warning) => warning.code === "tree_truncated")) throw workspaceError("[vitehub] GitHub workspace store could not merge because GitHub returned a truncated tree.");
854
+ return files;
855
+ }, "tree");
856
+ /**
857
+ * Merge with the Git data API when the Merges API conflicts: files that only one side changed take that side, and
858
+ * files that both changed keep the receiving ref's version. `onConflict` sees the files that stayed.
859
+ */
860
+ const mergeKeepingOurs = async (from, into, mergeOptions) => {
861
+ let metadata = mergeOptions.metadata;
862
+ const sha = await githubRequest(client(), async (provider, repo) => {
863
+ const oursSha = await provider.contents.resolveRef(repo, `heads/${into.branch}`);
864
+ const theirsSha = await provider.contents.resolveRef(repo, `heads/${from.branch}`);
865
+ if (!oursSha || !theirsSha) malformed("commit");
866
+ const compare = (await provider.request("GET", `${repoPath(repo)}/compare/${encodeURIComponent(oursSha)}...${encodeURIComponent(theirsSha)}`)).data;
867
+ const mergeBase = Reflect.get(Object(Reflect.get(Object(compare), "merge_base_commit")), "sha");
868
+ if (!nonEmptyString(mergeBase)) malformed("compare");
869
+ const [before, ours, theirs] = await Promise.all([
870
+ readFullTree(mergeBase),
871
+ readFullTree(oursSha),
872
+ readFullTree(theirsSha)
873
+ ]);
874
+ const same = (left, right) => left?.sha === right?.sha && left?.mode === right?.mode;
875
+ const changes = [];
876
+ const conflicts = [];
877
+ for (const path of /* @__PURE__ */ new Set([
878
+ ...before.keys(),
879
+ ...ours.keys(),
880
+ ...theirs.keys()
881
+ ])) {
882
+ const b = before.get(path);
883
+ const o = ours.get(path);
884
+ const t = theirs.get(path);
885
+ if (same(o, t) || same(t, b)) continue;
886
+ if (same(o, b)) {
887
+ changes.push({
888
+ mode: t?.mode ?? "100644",
889
+ path,
890
+ sha: t?.sha ?? null,
891
+ type: "blob"
892
+ });
893
+ continue;
894
+ }
895
+ const workspacePath = options.root ? path.startsWith(`${options.root}/`) ? path.slice(options.root.length + 1) : void 0 : path;
896
+ if (workspacePath !== void 0 && visibleWorkspacePath(workspacePath)) conflicts.push({
897
+ path: workspacePath,
898
+ ours: o?.sha ?? null,
899
+ theirs: t?.sha ?? null,
900
+ base: b?.sha ?? null
901
+ });
902
+ }
903
+ const resolution = await mergeOptions.onConflict(conflicts, { read: async (sha) => await forgeBlob(provider, repo, sha) });
904
+ metadata = {
905
+ ...mergeOptions.metadata,
906
+ ...resolution.metadata
907
+ };
908
+ for (const [path, text] of Object.entries(resolution.files ?? {})) {
909
+ if (!conflicts.some((conflict) => conflict.path === path)) throw workspaceError(`[vitehub] A merge resolved ${path}, which is not one of its conflicting files.`);
910
+ const repositoryPath = options.root ? `${options.root}/${path}` : path;
911
+ const blob = (await provider.request("POST", `${repoPath(repo)}/git/blobs`, { body: {
912
+ content: Buffer.from(text, "utf8").toString("base64"),
913
+ encoding: "base64"
914
+ } })).data;
915
+ const blobSha = Reflect.get(Object(blob), "sha");
916
+ if (!nonEmptyString(blobSha)) malformed("blob");
917
+ changes.push({
918
+ mode: ours.get(repositoryPath)?.mode ?? theirs.get(repositoryPath)?.mode ?? "100644",
919
+ path: repositoryPath,
920
+ sha: blobSha,
921
+ type: "blob"
922
+ });
923
+ }
924
+ const message = messageWithMetadata(mergeOptions.message ?? `Merge ${from.ref} into ${into.ref}`, metadata);
925
+ const oursTree = (await provider.request("GET", `${repoPath(repo)}/git/commits/${encodeURIComponent(oursSha)}`)).data;
926
+ const baseTree = Reflect.get(Object(Reflect.get(Object(oursTree), "tree")), "sha");
927
+ if (!nonEmptyString(baseTree)) malformed("commit");
928
+ let tree = baseTree;
929
+ if (changes.length) {
930
+ const created = (await provider.request("POST", `${repoPath(repo)}/git/trees`, { body: {
931
+ base_tree: baseTree,
932
+ tree: changes
933
+ } })).data;
934
+ const createdSha = Reflect.get(Object(created), "sha");
935
+ if (!nonEmptyString(createdSha)) malformed("tree");
936
+ tree = createdSha;
937
+ }
938
+ const commit = (await provider.request("POST", `${repoPath(repo)}/git/commits`, { body: {
939
+ message,
940
+ tree,
941
+ parents: [oursSha, theirsSha]
942
+ } })).data;
943
+ const commitSha = Reflect.get(Object(commit), "sha");
944
+ if (!nonEmptyString(commitSha)) malformed("commit");
945
+ await provider.request("PATCH", `${repoPath(repo)}/git/refs/heads/${refPath(into.branch)}`, { body: {
946
+ sha: commitSha,
947
+ force: false
948
+ } });
949
+ return commitSha;
950
+ }, "merge");
951
+ heads.set(into.branch, {
952
+ expires: Date.now() + githubHeadCacheMs,
953
+ head: Promise.resolve(sha)
954
+ });
955
+ return await revision(into.ref, sha, metadata);
956
+ };
957
+ const merge = async (mergeOptions) => {
958
+ const from = resolveRef(mergeOptions.from);
959
+ const into = resolveRef(mergeOptions.into);
960
+ const message = messageWithMetadata(mergeOptions.message ?? `Merge ${from.ref} into ${into.ref}`, mergeOptions.metadata);
961
+ let response;
962
+ for (let attempt = 1; !response; attempt++) try {
963
+ response = await githubRequest(client(), async (provider, repo) => await provider.request("POST", `${repoPath(repo)}/merges`, { body: {
964
+ base: into.branch,
965
+ head: from.branch,
966
+ commit_message: message
967
+ } }), "merge");
968
+ } catch (error) {
969
+ heads.delete(into.branch);
970
+ const status = githubRequestStatus(error);
971
+ if (isMergeConflict(error)) {
972
+ if (mergeOptions.onConflict) return await mergeKeepingOurs(from, into, mergeOptions);
973
+ throw workspaceConflict(`[vitehub] Merging ${from.ref} into ${into.ref} conflicts: the same lines changed on both. Resolve the conflict on the ${into.branch} branch, or make the change again after it.`, {
974
+ cause: error,
975
+ details: {
976
+ from: from.ref,
977
+ into: into.ref
978
+ }
979
+ });
980
+ }
981
+ if (status === 409 && attempt === 1) continue;
982
+ if (status === 404) throw workspaceError(`[vitehub] Cannot merge ${from.ref} into ${into.ref}: a branch does not exist.`, { cause: error });
983
+ throw error;
984
+ }
985
+ if (response.status === 204) return null;
986
+ const sha = response.data !== null && typeof response.data === "object" ? Reflect.get(response.data, "sha") : void 0;
987
+ if (!nonEmptyString(sha)) malformed("merge");
988
+ heads.set(into.branch, {
989
+ expires: Date.now() + githubHeadCacheMs,
990
+ head: Promise.resolve(sha)
991
+ });
992
+ return await revision(into.ref, sha, mergeOptions.metadata);
993
+ };
994
+ /** Prepare on an isolated ref so a denied or invalid merge never changes the destination. */
995
+ const checkedMerge = async (mergeOptions, check) => {
996
+ if (!check) return await merge(mergeOptions);
997
+ const into = resolveRef(mergeOptions.into);
998
+ const expected = await readCurrentHead(client(), into.branch);
999
+ if (!expected) throw workspaceError(`[vitehub] Cannot merge into ${into.ref}: the branch does not exist.`);
1000
+ const temporary = `vitehub/merge/${randomUUID()}`;
1001
+ await githubRequest(client(), async (provider, repo) => await provider.request("POST", `${repoPath(repo)}/git/refs`, { body: {
1002
+ ref: `refs/heads/${temporary}`,
1003
+ sha: expected
1004
+ } }));
1005
+ try {
1006
+ const prepared = await merge({
1007
+ ...mergeOptions,
1008
+ into: temporary,
1009
+ message: mergeOptions.message ?? `Merge ${mergeOptions.from} into ${into.ref}`
1010
+ });
1011
+ if (!prepared) return null;
1012
+ const [before, after] = await Promise.all([readFullTree(expected), readFullTree(prepared.id)]);
1013
+ for (const path of /* @__PURE__ */ new Set([...before.keys(), ...after.keys()])) {
1014
+ const workspacePath = options.root ? path.startsWith(`${options.root}/`) ? path.slice(options.root.length + 1) : void 0 : path;
1015
+ if (workspacePath !== void 0 && visibleWorkspacePath(workspacePath)) continue;
1016
+ if (before.get(path)?.sha !== after.get(path)?.sha || before.get(path)?.mode !== after.get(path)?.mode) throw workspaceError(`[vitehub] Cannot merge a change outside the Workspace file tree: ${path}.`);
1017
+ }
1018
+ const view = await open(prepared.id);
1019
+ const entries = (await view.list("", { recursive: true })).filter((entry) => entry.type === "file");
1020
+ const files = Object.create(null);
1021
+ for (const entry of entries) files[entry.path] = {
1022
+ path: entry.path,
1023
+ content: await view.readFile(entry.path, { encoding: "binary" }),
1024
+ mediaType: entry.mediaType,
1025
+ metadata: entry.metadata
1026
+ };
1027
+ return await check({
1028
+ ref: into.ref,
1029
+ ifHead: expected,
1030
+ files,
1031
+ message: prepared.message,
1032
+ metadata: prepared.metadata
1033
+ }, async (checked) => {
1034
+ const result = checked.changes !== void 0 || !checked.files || Object.keys(checked.files).length !== entries.length || (await Promise.all(entries.map(async (entry) => {
1035
+ const file = checked.files?.[entry.path];
1036
+ return !file || await gitBlobSha(contentToBytes(file.content)) !== entry.digest || gitFileMode(file.metadata?.gitMode ?? entry.metadata?.gitMode) !== gitFileMode(entry.metadata?.gitMode);
1037
+ }))).some(Boolean) ? await commit({
1038
+ ...checked,
1039
+ ref: temporary,
1040
+ ifHead: prepared.id
1041
+ }) : prepared;
1042
+ const actual = await readCurrentHead(client(), into.branch);
1043
+ if (actual !== expected) {
1044
+ heads.delete(into.branch);
1045
+ throw historyConflict(into.ref, expected, actual);
1046
+ }
1047
+ await githubRequest(client(), async (provider, repo) => await provider.request("PATCH", `${repoPath(repo)}/git/refs/heads/${refPath(into.branch)}`, { body: {
1048
+ sha: result.id,
1049
+ force: false
1050
+ } }));
1051
+ heads.set(into.branch, {
1052
+ expires: Date.now() + githubHeadCacheMs,
1053
+ head: Promise.resolve(result.id)
1054
+ });
1055
+ return await revision(into.ref, result.id, result.metadata);
1056
+ });
1057
+ } finally {
1058
+ await deleteBranch(temporary);
1059
+ }
1060
+ };
1061
+ return {
1062
+ pullRequests,
1063
+ openPullRequest,
1064
+ merge: checkedMerge,
1065
+ head: async (headOptions) => {
1066
+ const { branch, ref } = resolveRef(headOptions?.ref);
1067
+ const id = await readBranchHead(branch);
1068
+ return id ? await revision(ref, id) : null;
1069
+ },
1070
+ digest: gitBlobSha,
1071
+ forksFrom: async (ref) => options.refs?.published && ref !== "published" ? "published" : void 0,
1072
+ list,
1073
+ refs,
1074
+ open,
1075
+ usage,
1076
+ commit
1077
+ };
1078
+ }
1079
+ //#endregion
1080
+ //#region src/providers/github/store.ts
1081
+ const fileMetadataPrefix = ".vitehub/file-metadata/";
1082
+ function isFileMetadataPath(path) {
1083
+ return path.startsWith(fileMetadataPrefix) && path.endsWith(".json");
1084
+ }
1085
+ function fileMetadataPath(path) {
1086
+ return `${fileMetadataPrefix}${encodeURIComponent(path)}.json`;
1087
+ }
1088
+ function filePathFromMetadataPath(path) {
1089
+ try {
1090
+ return decodeURIComponent(path.slice(23, -5));
1091
+ } catch {
1092
+ return "";
1093
+ }
1094
+ }
1095
+ function portableMetadata(metadata) {
1096
+ return Object.fromEntries(Object.entries(metadata).filter(([key]) => key !== "gitMode" && key !== "symlinkTarget"));
1097
+ }
1098
+ function fileAttributesBytes(file) {
1099
+ const metadata = file.metadata && portableMetadata(file.metadata);
1100
+ if (file.mediaType === void 0 && (!metadata || Object.keys(metadata).length === 0)) return void 0;
1101
+ return contentToBytes(JSON.stringify({
1102
+ ...file.mediaType === void 0 ? {} : { mediaType: file.mediaType },
1103
+ ...metadata && Object.keys(metadata).length > 0 ? { metadata } : {}
1104
+ }));
1105
+ }
1106
+ function parseFileAttributes(bytes) {
1107
+ try {
1108
+ const value = JSON.parse(new TextDecoder().decode(bytes));
1109
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1110
+ const record = value;
1111
+ const metadata = record.metadata;
1112
+ return {
1113
+ ...typeof record.mediaType === "string" ? { mediaType: record.mediaType } : {},
1114
+ ...metadata && typeof metadata === "object" && !Array.isArray(metadata) ? { metadata: portableMetadata(metadata) } : {}
1115
+ };
1116
+ } catch {
1117
+ return {};
1118
+ }
1119
+ }
1120
+ function sameFileAttributes(left, right) {
1121
+ return left?.mediaType === right.mediaType && JSON.stringify(left?.metadata) === JSON.stringify(right.metadata);
1122
+ }
1123
+ function sameGitHubTreeEntry(left, right) {
1124
+ return left?.sha === right?.sha && left?.mode === right?.mode;
1125
+ }
1126
+ function matchesGitHubRemote(file, remote) {
1127
+ return file?.gitSha === remote?.sha && (file ? gitHubFileMode(file.metadata) : void 0) === remote?.mode;
1128
+ }
1129
+ function githubRemoteFile(path, entry, attributes) {
1130
+ const treeMetadata = gitHubFileMetadata(entry);
1131
+ const metadata = treeMetadata || attributes?.metadata ? {
1132
+ ...treeMetadata,
1133
+ ...attributes?.metadata
1134
+ } : void 0;
1135
+ return {
1136
+ gitSha: entry.sha,
1137
+ ...attributes?.mediaType === void 0 ? {} : { mediaType: attributes.mediaType },
1138
+ ...metadata ? { metadata } : {},
1139
+ path,
1140
+ size: entry.size
1141
+ };
1142
+ }
1143
+ function isReservedWorkspacePath(path) {
1144
+ const root = normalizeWorkspacePath(path).split("/")[0]?.toLowerCase();
1145
+ return root === ".git" || root === ".vitehub";
1146
+ }
1147
+ function readStringMetadata(metadata, key) {
1148
+ const value = metadata?.[key];
1149
+ return Object.prototype.toString.call(value) === "[object String]" ? String(value) : void 0;
1150
+ }
1151
+ function gitHubFileMetadata(entry) {
1152
+ return entry.mode === "100644" ? void 0 : { gitMode: entry.mode };
1153
+ }
1154
+ function gitHubFileMode(metadata) {
1155
+ return gitFileMode(metadata?.gitMode);
1156
+ }
1157
+ function inheritedGitHubFileMetadata(file, current) {
1158
+ if (file.metadata) return file.metadata;
1159
+ return current?.metadata?.gitMode === "100755" ? current.metadata : void 0;
1160
+ }
1161
+ function parentDirectories(path) {
1162
+ const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
1163
+ const directories = [];
1164
+ for (let index = 1; index < parts.length; index++) directories.push(parts.slice(0, index).join("/"));
1165
+ return directories;
1166
+ }
1167
+ function resolveSymlinkTarget(path, bytes) {
1168
+ const target = gitSymlinkTargetFromBytes(bytes);
1169
+ if (!target || target.startsWith("/")) return;
1170
+ const base = path.split("/").slice(0, -1).join("/");
1171
+ const resolved = posix.normalize(base ? `${base}/${target}` : target);
1172
+ if (!resolved || resolved === "." || resolved === ".." || resolved.startsWith("../")) return;
1173
+ return normalizeSafeWorkspacePath(resolved);
1174
+ }
1175
+ function gitSymlinkTargetFromBytes(bytes) {
1176
+ return new TextDecoder().decode(bytes).replace(/\0/g, "");
1177
+ }
1178
+ async function waitForGitHubOperation(read, signal) {
1179
+ signal?.throwIfAborted();
1180
+ if (!signal) return await read;
1181
+ return await new Promise((resolve, reject) => {
1182
+ const abort = () => reject(signal.reason);
1183
+ signal.addEventListener("abort", abort, { once: true });
1184
+ read.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
1185
+ });
1186
+ }
1187
+ var GitHubWorkspaceStore = class {
1188
+ options;
1189
+ workspaceName;
1190
+ #baseline;
1191
+ #archive;
1192
+ #archiveReads = /* @__PURE__ */ new Map();
1193
+ #baselineRefSha;
1194
+ #dirty = false;
1195
+ #files = /* @__PURE__ */ new Map();
1196
+ #mutationQueue = Promise.resolve();
1197
+ #ready;
1198
+ #remoteFiles = /* @__PURE__ */ new Map();
1199
+ #remoteMetadataFiles = /* @__PURE__ */ new Map();
1200
+ #resolved;
1201
+ #history;
1202
+ constructor(options, workspaceName) {
1203
+ this.options = options;
1204
+ this.workspaceName = workspaceName;
1205
+ }
1206
+ /**
1207
+ * The repository, branch, root, and token resolve on first use. The Store is created when the Workspace Definition
1208
+ * loads, even in a build that has no token, and a missing option fails at the first request.
1209
+ */
1210
+ get #connection() {
1211
+ return this.#resolved ||= (() => {
1212
+ const repository = requireGitHubOption("a repository", resolveGitHubRepositoryOption(this.options));
1213
+ const token = requireGitHubOption("a token", resolveGitHubTokenOption(this.options));
1214
+ return {
1215
+ branch: resolveGitHubBranchOption(this.options),
1216
+ client: connectGitHubRepository(repository, token),
1217
+ repository,
1218
+ root: resolveGitHubRootOption(this.options, this.workspaceName)
1219
+ };
1220
+ })();
1221
+ }
1222
+ get #branch() {
1223
+ return this.#connection.branch;
1224
+ }
1225
+ get #client() {
1226
+ return this.#connection.client;
1227
+ }
1228
+ get #repository() {
1229
+ return this.#connection.repository;
1230
+ }
1231
+ get #root() {
1232
+ return this.#connection.root;
1233
+ }
1234
+ get history() {
1235
+ return this.#history ||= createGitHubWorkspaceHistory(() => ({
1236
+ branch: this.#branch,
1237
+ client: this.#client,
1238
+ refs: resolveGitHubRefsOption(this.options),
1239
+ repository: this.#repository,
1240
+ root: this.#root
1241
+ }));
1242
+ }
1243
+ [workspaceStoreTarget]() {
1244
+ return {
1245
+ provider: "github",
1246
+ branch: this.#branch,
1247
+ repository: this.#repository,
1248
+ ...this.options.database === void 0 ? {} : { database: this.options.database }
1249
+ };
1250
+ }
1251
+ [workspaceRevisionMaterializer] = {
1252
+ currentRevision: async (options) => {
1253
+ await waitForGitHubOperation(this.#mutate(async () => await this.#ensure({ refresh: options?.refresh !== false })), options?.abortSignal);
1254
+ return this.#baselineRefSha;
1255
+ },
1256
+ materializeRevision: async (options) => {
1257
+ await waitForGitHubOperation(this.#mutate(async () => await this.#ensure({ refresh: true })), options?.abortSignal);
1258
+ const revision = this.#baselineRefSha;
1259
+ const paths = options?.paths;
1260
+ const files = [...this.#remoteFiles.keys()].filter((path) => !isReservedWorkspacePath(path) && (!paths || paths.some((root) => path === root || path.startsWith(`${root}/`)))).length;
1261
+ if (!this.#dirty && paths === void 0 && this.#archive?.revision !== revision) {
1262
+ let read = this.#archiveReads.get(revision);
1263
+ if (!read) {
1264
+ read = readGitHubArchive(this.#client, revision);
1265
+ this.#archiveReads.set(revision, read);
1266
+ read.finally(() => {
1267
+ if (this.#archiveReads.get(revision) === read) this.#archiveReads.delete(revision);
1268
+ }).catch(() => {});
1269
+ }
1270
+ this.#archive = {
1271
+ bytes: await waitForGitHubOperation(read, options?.abortSignal),
1272
+ revision
1273
+ };
1274
+ }
1275
+ return {
1276
+ ...!this.#dirty && paths === void 0 ? { archive: this.#archive.bytes } : {},
1277
+ files,
1278
+ paths,
1279
+ revision,
1280
+ root: this.#root
1281
+ };
1282
+ }
1283
+ };
1284
+ async readFile(path) {
1285
+ const normalized = normalizeSafeWorkspacePath(path);
1286
+ await this.#ensure({ refresh: false });
1287
+ return await this.#readWorkspaceFile(normalized);
1288
+ }
1289
+ async writeFile(path, file) {
1290
+ await this.#mutate(async () => {
1291
+ const normalized = normalizeSafeWorkspacePath(path);
1292
+ await this.#ensure({ refresh: false });
1293
+ await this.#writeFile(normalized, file);
1294
+ });
1295
+ }
1296
+ async writeFileConditional(path, file, ifDigest) {
1297
+ await this.#mutate(async () => {
1298
+ const normalized = normalizeSafeWorkspacePath(path);
1299
+ await this.#ensure({ refresh: true });
1300
+ assertWorkspaceDigest(normalized, ifDigest, this.#files.get(normalized)?.gitSha);
1301
+ await this.#writeFile(normalized, file);
1302
+ });
1303
+ }
1304
+ async #writeFile(normalized, file) {
1305
+ const current = this.#files.get(normalized);
1306
+ const metadata = inheritedGitHubFileMetadata(file, current);
1307
+ const symlinkTarget = readStringMetadata(metadata, "symlinkTarget");
1308
+ const content = gitHubFileMode(metadata) === "120000" && symlinkTarget !== void 0 ? symlinkTarget : file.content;
1309
+ const bytes = contentToBytes(content);
1310
+ const gitSha = await gitBlobSha(bytes);
1311
+ if (current?.gitSha === gitSha) {
1312
+ if (gitHubFileMode(current.metadata) !== gitHubFileMode(metadata) || !sameFileAttributes(current, {
1313
+ mediaType: file.mediaType,
1314
+ metadata
1315
+ })) this.#dirty = true;
1316
+ this.#files.set(normalized, {
1317
+ ...current,
1318
+ bytes,
1319
+ mediaType: file.mediaType,
1320
+ metadata,
1321
+ size: bytes.byteLength
1322
+ });
1323
+ return;
1324
+ }
1325
+ this.#files.set(normalized, {
1326
+ bytes,
1327
+ gitSha,
1328
+ mediaType: file.mediaType,
1329
+ metadata,
1330
+ path: normalized,
1331
+ size: bytes.byteLength
1332
+ });
1333
+ this.#dirty = true;
1334
+ }
1335
+ #mutate(operation) {
1336
+ const result = this.#mutationQueue.then(operation);
1337
+ this.#mutationQueue = result.then(() => void 0, () => void 0);
1338
+ return result;
1339
+ }
1340
+ async writeFileStream(path, file) {
1341
+ const content = await contentStreamToBytes(file.content);
1342
+ await this.writeFile(path, {
1343
+ path: file.path,
1344
+ content,
1345
+ mediaType: file.mediaType,
1346
+ metadata: file.metadata
1347
+ });
1348
+ return {
1349
+ digest: await gitBlobSha(content),
1350
+ mediaType: file.mediaType,
1351
+ path: normalizeSafeWorkspacePath(path),
1352
+ size: content.byteLength,
1353
+ type: "file"
1354
+ };
1355
+ }
1356
+ async list(prefix = "", options = {}) {
1357
+ return await this.#mutate(async () => {
1358
+ const normalizedPrefix = normalizeSafeWorkspacePath(prefix, { allowEmpty: true });
1359
+ await this.#ensure({ refresh: true });
1360
+ return await this.#listEntries(normalizedPrefix, options);
1361
+ });
1362
+ }
1363
+ async glob(pattern, options = {}) {
1364
+ const patterns = Array.isArray(pattern) ? pattern.map(normalizeSafeWorkspacePattern) : normalizeSafeWorkspacePattern(pattern);
1365
+ const { cwd, matches } = createWorkspaceGlobMatcher(patterns, options);
1366
+ return (await this.list(cwd, { recursive: true })).filter((entry) => entry.type === "file" && matches(entry.path));
1367
+ }
1368
+ async stat(path) {
1369
+ return await this.#mutate(async () => {
1370
+ const normalized = normalizeSafeWorkspacePath(path);
1371
+ await this.#ensure({ refresh: true });
1372
+ const file = this.#files.get(normalized);
1373
+ if (file && !isReservedWorkspacePath(normalized)) return this.#fileEntry(file);
1374
+ if (this.#directoryExists(normalized)) return {
1375
+ path: normalized,
1376
+ type: "directory"
1377
+ };
1378
+ });
1379
+ }
1380
+ async mkdir(path, _options = {}) {
1381
+ normalizeSafeWorkspacePath(path);
1382
+ }
1383
+ async rm(path, options = {}) {
1384
+ await this.#mutate(async () => {
1385
+ const normalized = normalizeSafeWorkspacePath(path);
1386
+ await this.#ensure({ refresh: false });
1387
+ const file = this.#files.get(normalized);
1388
+ if (options.ifDigest !== void 0) assertWorkspaceDigest(path, options.ifDigest, file ? (await this.#fileEntry(file)).digest : void 0);
1389
+ const removedFile = Boolean(file && !isReservedWorkspacePath(normalized));
1390
+ if (removedFile) {
1391
+ this.#files.delete(normalized);
1392
+ this.#dirty = true;
1393
+ if (!options.recursive) return;
1394
+ }
1395
+ const children = this.#publicDescendants(normalized);
1396
+ if (!(children.length > 0)) {
1397
+ if (removedFile || options.force) return;
1398
+ throw workspaceError(`[vitehub] Workspace path does not exist: ${path}.`);
1399
+ }
1400
+ if (children.length && !options.recursive) throw workspaceError(`[vitehub] Workspace directory is not empty: ${path}.`);
1401
+ for (const child of children) this.#files.delete(child);
1402
+ this.#dirty = true;
1403
+ });
1404
+ }
1405
+ async snapshot(options = {}) {
1406
+ return await this.#mutate(async () => await this.#snapshot(options));
1407
+ }
1408
+ async rebase(options = {}) {
1409
+ await this.#mutate(async () => {
1410
+ 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");
1455
+ for (const path of changed) {
1456
+ if (shouldTakeRemote(path)) continue;
1457
+ const file = local.get(path);
1458
+ if (file) this.#files.set(path, file);
1459
+ else this.#files.delete(path);
1460
+ }
1461
+ this.#dirty = await this.#hasRemoteChanges();
1462
+ });
1463
+ }
1464
+ async #snapshot(options) {
1465
+ await this.#ensure({ refresh: false });
1466
+ const snapshot = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }), options.name);
1467
+ if (!this.#dirty) {
1468
+ this.#baseline = snapshot;
1469
+ return snapshot;
1470
+ }
1471
+ const remote = await readGitHubBranchState({
1472
+ branch: this.#branch,
1473
+ repository: this.#client,
1474
+ root: this.#root
1475
+ });
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
+ });
1482
+ const remoteFiles = new Map([...remote.files].filter(([path]) => !isFileMetadataPath(path)));
1483
+ const remoteMetadataFiles = new Map([...remote.files].filter(([path]) => isFileMetadataPath(path)));
1484
+ this.#remoteFiles = remoteFiles;
1485
+ this.#remoteMetadataFiles = remoteMetadataFiles;
1486
+ this.#baselineRefSha = remote.refSha;
1487
+ const changedFiles = [...this.#files.values()].filter((file) => !matchesGitHubRemote(file, this.#remoteFiles.get(file.path)));
1488
+ const changedMetadataFiles = (await Promise.all([...this.#files.values()].map(async (file) => {
1489
+ const bytes = fileAttributesBytes(file);
1490
+ const remote = this.#remoteMetadataFiles.get(fileMetadataPath(file.path));
1491
+ if (!bytes) return void 0;
1492
+ return remote?.sha === await gitBlobSha(bytes) ? void 0 : file;
1493
+ }))).filter((file) => Boolean(file));
1494
+ const deletePaths = [...this.#remoteFiles].filter(([path]) => !this.#files.has(path)).map(([, entry]) => entry.path).concat([...this.#remoteMetadataFiles].filter(([path]) => !this.#files.has(filePathFromMetadataPath(path)) || !fileAttributesBytes(this.#files.get(filePathFromMetadataPath(path)))).map(([, entry]) => entry.path));
1495
+ if (!changedFiles.length && !changedMetadataFiles.length && !deletePaths.length) {
1496
+ this.#dirty = false;
1497
+ this.#baseline = snapshot;
1498
+ return snapshot;
1499
+ }
1500
+ const files = await Promise.all(changedFiles.map(async (file) => ({
1501
+ bytes: await this.#readFileBytes(file),
1502
+ fullPath: joinGitPath(this.#root, file.path),
1503
+ mode: gitHubFileMode(file.metadata)
1504
+ })));
1505
+ for (const file of changedMetadataFiles) {
1506
+ const bytes = fileAttributesBytes(file);
1507
+ if (bytes) files.push({
1508
+ bytes,
1509
+ fullPath: joinGitPath(this.#root, fileMetadataPath(file.path)),
1510
+ mode: "100644"
1511
+ });
1512
+ }
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
+ });
1523
+ this.#dirty = false;
1524
+ this.#baselineRefSha = commitSha;
1525
+ this.#remoteFiles = this.#toRemoteFiles();
1526
+ this.#remoteMetadataFiles = await this.#toRemoteMetadataFiles();
1527
+ this.#baseline = {
1528
+ ...snapshot,
1529
+ id: commitSha
1530
+ };
1531
+ return this.#baseline;
1532
+ }
1533
+ async diff(options = {}) {
1534
+ return await this.#mutate(async () => {
1535
+ await this.#ensure({ refresh: true });
1536
+ const fromSnapshot = options.from || this.#baseline;
1537
+ const from = fromSnapshot && {
1538
+ ...fromSnapshot,
1539
+ entries: Object.fromEntries(Object.entries(fromSnapshot.entries).map(([path, entry]) => [path, {
1540
+ ...entry,
1541
+ ...entry.metadata?.gitMode === "120000" ? { metadata: {
1542
+ ...entry.metadata,
1543
+ symlinkTarget: void 0
1544
+ } } : {}
1545
+ }]))
1546
+ };
1547
+ const to = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }, false));
1548
+ return diffSnapshots(from, to);
1549
+ });
1550
+ }
1551
+ async getMeta(key) {
1552
+ return await this.#mutate(async () => {
1553
+ await this.#ensure({ refresh: true });
1554
+ const file = await this.#readWorkspaceFile(this.#metaPath(key));
1555
+ if (!file) return void 0;
1556
+ return JSON.parse(new TextDecoder().decode(file.bytes));
1557
+ });
1558
+ }
1559
+ async setMeta(key, value) {
1560
+ await this.#mutate(async () => {
1561
+ const path = this.#metaPath(key);
1562
+ const content = JSON.stringify(value);
1563
+ const bytes = new TextEncoder().encode(content);
1564
+ await this.#ensure({ refresh: false });
1565
+ this.#files.set(path, {
1566
+ bytes,
1567
+ gitSha: await gitBlobSha(bytes),
1568
+ path,
1569
+ size: bytes.byteLength
1570
+ });
1571
+ this.#dirty = true;
1572
+ });
1573
+ }
1574
+ async #ensure(options) {
1575
+ const wasReady = !!this.#ready;
1576
+ this.#ready ||= this.#load();
1577
+ await this.#ready;
1578
+ if (wasReady && options.refresh && !this.#dirty) await this.#load();
1579
+ }
1580
+ async #matchesRemote(file, remote, remoteMetadata) {
1581
+ if (!matchesGitHubRemote(file, remote)) return false;
1582
+ const attributes = file && fileAttributesBytes(file);
1583
+ if (!attributes) return !remoteMetadata;
1584
+ return remoteMetadata?.sha === await gitBlobSha(attributes);
1585
+ }
1586
+ async #hasRemoteChanges() {
1587
+ const paths = /* @__PURE__ */ new Set([...this.#remoteFiles.keys(), ...this.#files.keys()]);
1588
+ for (const path of paths) if (!await this.#matchesRemote(this.#files.get(path), this.#remoteFiles.get(path), this.#remoteMetadataFiles.get(fileMetadataPath(path)))) return true;
1589
+ return false;
1590
+ }
1591
+ async #load() {
1592
+ const previousFiles = this.#files;
1593
+ const remote = await readGitHubBranchState({
1594
+ branch: this.#branch,
1595
+ repository: this.#client,
1596
+ root: this.#root
1597
+ });
1598
+ this.#baselineRefSha = remote.refSha;
1599
+ const remoteFiles = new Map([...remote.files].filter(([path]) => !isFileMetadataPath(path)));
1600
+ const remoteMetadataFiles = new Map([...remote.files].filter(([path]) => isFileMetadataPath(path)));
1601
+ const attributes = /* @__PURE__ */ new Map();
1602
+ await Promise.all([...remoteMetadataFiles].map(async ([path, entry]) => {
1603
+ const bytes = await readGitHubFile(this.#client, entry, remote.refSha);
1604
+ attributes.set(filePathFromMetadataPath(path), parseFileAttributes(bytes));
1605
+ }));
1606
+ this.#remoteFiles = remoteFiles;
1607
+ this.#remoteMetadataFiles = remoteMetadataFiles;
1608
+ if (!this.#dirty) {
1609
+ this.#files = new Map([...remoteFiles].map(([path, entry]) => {
1610
+ const previous = previousFiles.get(path);
1611
+ return [path, {
1612
+ ...githubRemoteFile(path, entry, attributes.get(path)),
1613
+ ...previous && previous.gitSha === entry.sha && gitHubFileMode(previous.metadata) === entry.mode ? { bytes: previous.bytes } : {}
1614
+ }];
1615
+ }));
1616
+ this.#baseline = await createSnapshotFromEntries(await this.#listEntries("", { recursive: true }, false), "github-workspace-store-load");
1617
+ }
1618
+ }
1619
+ async #readWorkspaceFile(path, seen = /* @__PURE__ */ new Set()) {
1620
+ const current = this.#files.get(path);
1621
+ if (!current) return void 0;
1622
+ const currentBytes = await this.#readFileBytes(current);
1623
+ if (gitHubFileMode(current.metadata) === "120000" && !seen.has(path)) {
1624
+ const target = resolveSymlinkTarget(path, currentBytes);
1625
+ if (target && this.#files.has(target)) {
1626
+ seen.add(path);
1627
+ const resolved = await this.#readWorkspaceFile(target, seen);
1628
+ if (resolved) return {
1629
+ ...resolved,
1630
+ mediaType: current.mediaType ?? resolved.mediaType,
1631
+ metadata: await this.#fileMetadata(current) ?? resolved.metadata,
1632
+ path
1633
+ };
1634
+ }
1635
+ }
1636
+ return {
1637
+ content: currentBytes,
1638
+ bytes: currentBytes,
1639
+ mediaType: current.mediaType,
1640
+ metadata: await this.#fileMetadata(current),
1641
+ path
1642
+ };
1643
+ }
1644
+ async #readFileBytes(file) {
1645
+ if (!file.bytes) {
1646
+ file.bytes = await readGitHubFile(this.#client, {
1647
+ mode: gitHubFileMode(file.metadata),
1648
+ path: joinGitPath(this.#root, file.path),
1649
+ sha: file.gitSha
1650
+ }, this.#baselineRefSha);
1651
+ file.size = file.bytes.byteLength;
1652
+ }
1653
+ return file.bytes;
1654
+ }
1655
+ async #fileMetadata(file) {
1656
+ if (gitHubFileMode(file.metadata) !== "120000" || readStringMetadata(file.metadata, "symlinkTarget") !== void 0) return file.metadata;
1657
+ return {
1658
+ ...file.metadata,
1659
+ symlinkTarget: gitSymlinkTargetFromBytes(await this.#readFileBytes(file))
1660
+ };
1661
+ }
1662
+ async #listEntries(prefix, options, resolveSymlinks = true) {
1663
+ const entries = /* @__PURE__ */ new Map();
1664
+ for (const file of this.#files.values()) {
1665
+ if (isReservedWorkspacePath(file.path) || isExcludedWorkspacePath(file.path, options.exclude)) continue;
1666
+ for (const dir of parentDirectories(file.path)) {
1667
+ if (isExcludedWorkspacePath(dir, options.exclude)) continue;
1668
+ if (this.#entryInPrefix(dir, prefix, options)) entries.set(dir, {
1669
+ path: dir,
1670
+ type: "directory"
1671
+ });
1672
+ }
1673
+ if (this.#entryInPrefix(file.path, prefix, options)) entries.set(file.path, await this.#fileEntry(file, resolveSymlinks));
1674
+ }
1675
+ return [...entries.values()].sort((a, b) => a.path.localeCompare(b.path));
1676
+ }
1677
+ #entryInPrefix(path, prefix, options) {
1678
+ if (!prefix) return options.recursive || !path.includes("/");
1679
+ if (path === prefix) return false;
1680
+ if (!path.startsWith(`${prefix}/`)) return false;
1681
+ return options.recursive || !path.slice(prefix.length + 1).includes("/");
1682
+ }
1683
+ async #fileEntry(file, resolveSymlinks = true) {
1684
+ return {
1685
+ digest: file.gitSha,
1686
+ mediaType: file.mediaType,
1687
+ metadata: resolveSymlinks ? await this.#fileMetadata(file) : file.metadata,
1688
+ path: file.path,
1689
+ size: file.size,
1690
+ type: "file"
1691
+ };
1692
+ }
1693
+ #directoryExists(path) {
1694
+ return this.#publicDescendants(path).length > 0;
1695
+ }
1696
+ #publicDescendants(path) {
1697
+ return [...this.#files.keys()].filter((key) => !isReservedWorkspacePath(key) && key.startsWith(`${path}/`));
1698
+ }
1699
+ #metaPath(key) {
1700
+ const normalized = normalizeSafeWorkspacePath(key.endsWith(".json") ? key : `${key}.json`, { allowReserved: true });
1701
+ return normalizeSafeWorkspacePath(`.vitehub/meta/${normalized}`, { allowReserved: true });
1702
+ }
1703
+ #toRemoteFiles() {
1704
+ return new Map([...this.#files.values()].map((file) => [file.path, {
1705
+ mode: gitHubFileMode(file.metadata),
1706
+ path: joinGitPath(this.#root, file.path),
1707
+ sha: file.gitSha,
1708
+ size: file.size
1709
+ }]));
1710
+ }
1711
+ async #toRemoteMetadataFiles() {
1712
+ const entries = await Promise.all([...this.#files.values()].map(async (file) => {
1713
+ const bytes = fileAttributesBytes(file);
1714
+ if (!bytes) return void 0;
1715
+ return [fileMetadataPath(file.path), {
1716
+ mode: "100644",
1717
+ path: joinGitPath(this.#root, fileMetadataPath(file.path)),
1718
+ sha: await gitBlobSha(bytes),
1719
+ size: bytes.byteLength
1720
+ }];
1721
+ }));
1722
+ return new Map(entries.filter((entry) => entry !== void 0));
1723
+ }
1724
+ };
1725
+ function createGitHubWorkspaceStore(options, workspaceName) {
1726
+ return new GitHubWorkspaceStore(options, workspaceName);
1727
+ }
1728
+ //#endregion
1729
+ export { forwardWorkspaceRevisionMaterializer as n, resolveWorkspaceRevisionMaterializer as r, createGitHubWorkspaceStore as t };