@vite-hub/workspace 0.0.4 → 0.3.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 (137) hide show
  1. package/README.md +339 -115
  2. package/dist/abort-BCwpdrN0.js +32 -0
  3. package/dist/{asset-registry-8QI3ML3K.js → asset-registry-DfBV5kmw.js} +3 -2
  4. package/dist/blob-database.d.ts +474 -0
  5. package/dist/blob-database.js +608 -0
  6. package/dist/checkout.d.ts +128 -0
  7. package/dist/checkout.js +849 -0
  8. package/dist/cloudflare.d.ts +6 -7
  9. package/dist/cloudflare.js +1 -1
  10. package/dist/config-B-863EgC.js +15 -0
  11. package/dist/config-BAgL2dtB.js +1076 -0
  12. package/dist/{config-DE9xlaIw.d.ts → config-BQKcPawI.d.ts} +1 -2
  13. package/dist/discard-CNNtCozM.js +8 -0
  14. package/dist/durability.d.ts +22 -0
  15. package/dist/durability.js +70 -0
  16. package/dist/error-diagnostics-CtKjGtGb.js +188 -0
  17. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  18. package/dist/file-2pFYNtsU.js +22 -0
  19. package/dist/{files-Q6xZjDHA.js → files-BOo4SbwE.js} +3 -3
  20. package/dist/files.d.ts +38 -0
  21. package/dist/files.js +6 -0
  22. package/dist/{github-DHnjxQIX.js → github-CrYp4v8k.js} +44 -24
  23. package/dist/glob-B8YGvTrZ.js +21 -0
  24. package/dist/glob-Cjxms1t7.js +30 -0
  25. package/dist/{host-DJH8cuoU.js → host-BFBpXn0N.js} +144 -77
  26. package/dist/{hosted-RPeJOCFz.js → hosted-KcUR_jPv.js} +303 -97
  27. package/dist/hosted-vercel-blob-B3-wRdUm.js +410 -0
  28. package/dist/hosted-vercel-blob.d.ts +6 -7
  29. package/dist/hosted-vercel-blob.js +1 -1
  30. package/dist/hosted.d.ts +10 -9
  31. package/dist/hosted.js +2 -2
  32. package/dist/index.d.ts +26 -47
  33. package/dist/index.js +30 -100
  34. package/dist/internal/path.d.ts +2 -0
  35. package/dist/internal/path.js +2 -0
  36. package/dist/lifecycle-B-enk_4A.js +596 -0
  37. package/dist/lineage.d.ts +26 -0
  38. package/dist/lineage.js +76 -0
  39. package/dist/loader.d.ts +5 -6
  40. package/dist/loader.js +3 -2
  41. package/dist/mcp-resources-DF0F5rcL.js +39 -0
  42. package/dist/memory-BOexthyW.js +247 -0
  43. package/dist/metadata-target-CWz6KHKq.js +1589 -0
  44. package/dist/object-Da1zyPCR.js +11 -0
  45. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  46. package/dist/operations-C6FpR8Rr.js +389 -0
  47. package/dist/operations-CE2drFih.js +1234 -0
  48. package/dist/operations.d.ts +90 -0
  49. package/dist/operations.js +3 -0
  50. package/dist/path--wrT_Azm.js +113 -0
  51. package/dist/path-AxMho1wo.d.ts +7 -0
  52. package/dist/path-DrSIenjj.js +59 -0
  53. package/dist/path-zHxQUbqa.d.ts +9 -0
  54. package/dist/plugins-C8C0auoW.d.ts +10 -0
  55. package/dist/provider-9s4Ufkm5.js +1479 -0
  56. package/dist/providers/github/store.d.ts +3 -5
  57. package/dist/providers/github/store.js +1 -1
  58. package/dist/registry-B3BBm4Ts.d.ts +19 -0
  59. package/dist/{registry-D3yzt8HQ.js → registry-CNphafBx.js} +60 -23
  60. package/dist/registry-CYNN623b.d.ts +9 -0
  61. package/dist/request-scope-Dw5n8bMC.js +83 -0
  62. package/dist/results-DgkZUmTL.js +8 -0
  63. package/dist/{chunk-2rV9d50f.js → rolldown-runtime-rQ84J-ij.js} +3 -4
  64. package/dist/runtime/assets.d.ts +3 -5
  65. package/dist/runtime/assets.js +7 -6
  66. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  67. package/dist/runtime/empty-registry.d.ts +2 -2
  68. package/dist/runtime/registry.d.ts +2 -0
  69. package/dist/runtime/registry.js +23 -0
  70. package/dist/runtime/request.d.ts +4 -0
  71. package/dist/runtime/request.js +8 -0
  72. package/dist/runtime/state.d.ts +5 -4
  73. package/dist/runtime/state.js +8 -18
  74. package/dist/runtime/workspace.d.ts +1 -1
  75. package/dist/runtime/workspace.js +1 -1
  76. package/dist/runtime.d.ts +52 -17
  77. package/dist/runtime.js +324 -67
  78. package/dist/{search-BpiCF2Tw.js → search-C_RfoM2j.js} +10 -9
  79. package/dist/server-8tGltlGz.js +303 -0
  80. package/dist/server.d.ts +36 -39
  81. package/dist/server.js +2 -328
  82. package/dist/shared-B3_EUk89.js +848 -0
  83. package/dist/source-metadata.d.ts +10 -7
  84. package/dist/source-metadata.js +12 -12
  85. package/dist/state-BISnUf1s.d.ts +35 -0
  86. package/dist/{ai-BqCC8BpY.js → state-DbrW-njQ.js} +237 -114
  87. package/dist/store-ybhyD38Z.js +1873 -0
  88. package/dist/{sync-DnTQwt8r.js → sync-CCD_VYC8.js} +61 -41
  89. package/dist/target-jWhTdIuF.js +89 -0
  90. package/dist/test.d.ts +1 -1
  91. package/dist/test.js +1 -1
  92. package/dist/{types-CYuwjJ4V.d.ts → types-BbtwmBZ5.d.ts} +321 -35
  93. package/dist/use-C6lV3-wC.d.ts +321 -0
  94. package/dist/{use-BTNDR5Rd.js → use-CSpT5W87.js} +141 -107
  95. package/dist/utils-CgMZCHsX.js +616 -0
  96. package/dist/vite.d.ts +585 -2
  97. package/dist/vite.js +21369 -2
  98. package/dist/workspace-CYB2xZ1T.d.ts +7 -0
  99. package/dist/{workspace-Dq08Yn72.js → workspace-sPWn2Jxj.js} +441 -225
  100. package/package.json +97 -72
  101. package/dist/ai-CjxvGqM0.d.ts +0 -162
  102. package/dist/ai.d.ts +0 -3
  103. package/dist/ai.js +0 -2
  104. package/dist/collections/client.d.ts +0 -39
  105. package/dist/collections/client.js +0 -137
  106. package/dist/collections.d.ts +0 -59
  107. package/dist/collections.js +0 -159
  108. package/dist/config-Bc3c4Su1.js +0 -7904
  109. package/dist/config-CHLLWklZ.js +0 -36
  110. package/dist/file-Bc1X7pco.js +0 -23
  111. package/dist/glob-CEZKeZFC.js +0 -18
  112. package/dist/hosted-vercel-blob-d6C8ND5j.js +0 -23580
  113. package/dist/lifecycle-LrL3sA4n.js +0 -316
  114. package/dist/metadata-target-B0tOmVW7.js +0 -717
  115. package/dist/mountx.d.ts +0 -10
  116. package/dist/mountx.js +0 -143
  117. package/dist/nitro.d.ts +0 -2
  118. package/dist/nitro.js +0 -2
  119. package/dist/nuxt.d.ts +0 -26
  120. package/dist/nuxt.js +0 -42
  121. package/dist/path-Cp59koVz.js +0 -139
  122. package/dist/provider-B1yLjCJJ.js +0 -746
  123. package/dist/publish.d.ts +0 -35
  124. package/dist/publish.js +0 -112
  125. package/dist/registry-Uj6IVxes.d.ts +0 -11
  126. package/dist/request-execution-B-dSFlGB.js +0 -84
  127. package/dist/runtime-options-BsPSv5O7.js +0 -13
  128. package/dist/runtime-type-iEE6BjQJ.js +0 -34
  129. package/dist/shared-DTR1Hhma.js +0 -331
  130. package/dist/state-tYcRWEh2.d.ts +0 -26
  131. package/dist/store-Dt_Jyys3.js +0 -608
  132. package/dist/target-D4Bqb1eH.js +0 -11
  133. package/dist/token-CVzURBxC.js +0 -61
  134. package/dist/use-BiHzt0xA.d.ts +0 -103
  135. package/dist/vite-BptCrpv2.js +0 -4526
  136. package/dist/vite-CtA9guIM.d.ts +0 -66
  137. package/dist/workspace-Xddf4G1B.d.ts +0 -6
@@ -0,0 +1,1479 @@
1
+ import { r as vitehubOwnedPrefix, t as createMemoryWorkspaceStore } from "./memory-BOexthyW.js";
2
+ import { n as assertWorkspaceDigest, o as workspaceConflictError, s as workspaceError } from "./path-DrSIenjj.js";
3
+ import { o as copyJsonFileMetadata, r as workspaceStoreTarget } from "./target-jWhTdIuF.js";
4
+ import { a as isExcludedWorkspacePath, d as resolveInside, f as sha256, l as normalizeWorkspacePath, r as contentToBytes, t as contentStreamChunks } from "./path--wrT_Azm.js";
5
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
6
+ import { t as createWorkspaceGlobMatcher } from "./glob-Cjxms1t7.js";
7
+ import { D as forgeEnv, O as readForgeEnv } from "./shared-B3_EUk89.js";
8
+ import { t as createGitHubWorkspaceStore } from "./store-ybhyD38Z.js";
9
+ import { t as getWorkspaceRuntimeConfig } from "./config-B-863EgC.js";
10
+ import { dirname, join, relative, resolve, sep } from "node:path";
11
+ import { createHash, randomUUID } from "node:crypto";
12
+ import { constants, createReadStream, createWriteStream } from "node:fs";
13
+ import { chmod, chown, copyFile, link, lstat, mkdir, open, readFile, readdir, rename, rm, rmdir, stat, utimes, writeFile } from "node:fs/promises";
14
+ import { defu } from "defu";
15
+ import { check, fallback, literal, object, optional, pipe, record, safeParse, string, unknown } from "valibot";
16
+ import { Readable, Transform } from "node:stream";
17
+ import { pipeline } from "node:stream/promises";
18
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
19
+ //#region ../internal/src/env.ts
20
+ function trimmed(value) {
21
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
22
+ }
23
+ function readEnv(env, ...names) {
24
+ for (const name of names) {
25
+ const value = trimmed(env[name]);
26
+ if (value) return value;
27
+ }
28
+ }
29
+ //#endregion
30
+ //#region src/runtime/hosted-store-loader.ts
31
+ const workspaceHostedStoreLoaderKey = Symbol.for("vitehub.workspace.hostedStoreLoader");
32
+ function workspaceHostedStoreLoaderGlobal() {
33
+ return globalThis;
34
+ }
35
+ function setWorkspaceHostedStoreLoader(loader) {
36
+ workspaceHostedStoreLoaderGlobal()[workspaceHostedStoreLoaderKey] = loader;
37
+ }
38
+ function getWorkspaceHostedStoreLoader() {
39
+ return workspaceHostedStoreLoaderGlobal()[workspaceHostedStoreLoaderKey];
40
+ }
41
+ //#endregion
42
+ //#region src/storage/local.ts
43
+ const fileMetadataSchema = optional(pipe(unknown(), check((value) => !Array.isArray(value)), record(string(), unknown()), check((value) => {
44
+ return safeParse(optional(string()), value.source).success;
45
+ })));
46
+ function assertFileMetadata(path, metadata) {
47
+ metadata = copyJsonFileMetadata(path, metadata);
48
+ if (!safeParse(fileMetadataSchema, metadata).success) throw workspaceError(`[vitehub] Invalid Workspace metadata for ${path}. metadata.source must be a string when provided.`);
49
+ return metadata;
50
+ }
51
+ async function backupFile(path, backup) {
52
+ try {
53
+ await link(path, backup);
54
+ } catch (error) {
55
+ if (![
56
+ "EPERM",
57
+ "ENOTSUP",
58
+ "EOPNOTSUPP",
59
+ "ENOSYS",
60
+ "EXDEV"
61
+ ].includes(Reflect.get(Object(error), "code"))) throw error;
62
+ const original = await stat(path);
63
+ try {
64
+ await copyFile(path, backup, constants.COPYFILE_EXCL);
65
+ const copied = await stat(backup);
66
+ if (process.platform !== "win32" && copied.gid !== original.gid) await chown(backup, copied.uid, original.gid);
67
+ await chmod(backup, original.mode & (copied.uid === original.uid ? 4095 : 511));
68
+ await utimes(backup, original.atime, original.mtime);
69
+ if (process.platform !== "win32" && copied.uid !== original.uid) return original.uid;
70
+ } catch (error) {
71
+ await rm(backup, { force: true }).catch(() => void 0);
72
+ throw error;
73
+ }
74
+ }
75
+ }
76
+ async function restoreBackup(backup, path, foreignUid, publicationError) {
77
+ if (foreignUid !== void 0) throw new AggregateError([publicationError], `[vitehub] Cannot roll back ${path} without changing owner UID ${foreignUid}. Recovery content remains at ${backup}.`);
78
+ await rename(backup, path);
79
+ }
80
+ async function reclaimBackup(path, retryDelay = 1e3, attempts = 0) {
81
+ try {
82
+ if (!path.endsWith(".committed.bak")) {
83
+ const committed = path.replace(/\.bak$/, ".committed.bak");
84
+ await rename(path, committed).catch((error) => {
85
+ if (error.code !== "ENOENT") throw error;
86
+ });
87
+ path = committed;
88
+ }
89
+ await rm(path, { force: true });
90
+ } catch {
91
+ if (attempts >= 5) return;
92
+ setTimeout(() => {
93
+ reclaimBackup(path, Math.min(retryDelay * 2, 3e4), attempts + 1);
94
+ }, retryDelay).unref();
95
+ }
96
+ }
97
+ async function reclaimCommittedBackups(root) {
98
+ const entries = await readdir(root).catch(() => []);
99
+ await Promise.all(entries.filter((name) => /^[0-9a-f-]{36}\.committed\.bak$/.test(name)).map((name) => reclaimBackup(`${root}/${name}`)));
100
+ }
101
+ function assertTrustedMetadata(path, info, root) {
102
+ const sharedGroup = (root.mode & 16) !== 0 && info.gid === root.gid;
103
+ const trustedOwner = info.uid === root.uid || info.uid === process.geteuid?.() || sharedGroup;
104
+ if (info.isSymbolicLink() || process.platform !== "win32" && (!trustedOwner || (info.mode & 2) !== 0 || (info.mode & 16) !== 0 && !sharedGroup)) throw workspaceError(`[vitehub] Untrusted Workspace metadata path: ${path}.`);
105
+ }
106
+ async function applyMetadataPermissions(path, mode, gid) {
107
+ const info = await stat(path);
108
+ if (info.gid !== gid) try {
109
+ await chown(path, info.uid, gid);
110
+ } catch (error) {
111
+ if (!["EPERM", "EACCES"].includes(Reflect.get(Object(error), "code"))) throw error;
112
+ mode &= 448;
113
+ }
114
+ if ((info.mode & 511) !== mode) try {
115
+ await chmod(path, mode);
116
+ } catch (error) {
117
+ if (!["EPERM", "EACCES"].includes(Reflect.get(Object(error), "code"))) throw error;
118
+ if ((info.mode & 511 & ~mode) !== 0) throw error;
119
+ }
120
+ }
121
+ async function validateLockDirectory(path) {
122
+ const info = await lstat(path).catch((error) => {
123
+ if (error.code === "ENOENT") return void 0;
124
+ throw error;
125
+ });
126
+ if (info && (!info.isDirectory() || info.isSymbolicLink())) throw workspaceError(`[vitehub] Untrusted Workspace lock path: ${path}.`);
127
+ }
128
+ async function ensureLockDirectory(path) {
129
+ await mkdir(path, { mode: 448 }).catch((error) => {
130
+ if (error.code !== "EEXIST") throw error;
131
+ });
132
+ await validateLockDirectory(path);
133
+ }
134
+ async function withLeaseHeartbeat(file, operation, onFailure) {
135
+ let renewal = Promise.resolve();
136
+ let rejectHeartbeat;
137
+ const heartbeatFailure = new Promise((_, reject) => {
138
+ rejectHeartbeat = reject;
139
+ });
140
+ heartbeatFailure.catch(() => {});
141
+ const timer = setInterval(() => {
142
+ renewal = renewal.then(async () => {
143
+ const now = /* @__PURE__ */ new Date();
144
+ await file.utimes(now, now);
145
+ });
146
+ renewal.catch((error) => {
147
+ rejectHeartbeat(error);
148
+ onFailure?.(error);
149
+ });
150
+ }, 3e4);
151
+ timer.unref();
152
+ const active = Promise.resolve().then(operation);
153
+ try {
154
+ return await Promise.race([active, heartbeatFailure]);
155
+ } catch (error) {
156
+ await active.catch(() => void 0);
157
+ throw error;
158
+ } finally {
159
+ clearInterval(timer);
160
+ try {
161
+ await renewal;
162
+ } finally {
163
+ await file.close();
164
+ }
165
+ }
166
+ }
167
+ async function removeOwnedGate(lock) {
168
+ for (let attempt = 0;; attempt++) try {
169
+ await rm(lock, {
170
+ force: true,
171
+ recursive: true
172
+ });
173
+ return;
174
+ } catch (error) {
175
+ if (attempt >= 2) throw error;
176
+ await setTimeout$1(25);
177
+ }
178
+ }
179
+ async function withFilesystemLock(lock, permissions, description, operation, deadline) {
180
+ const expiresAt = Date.now() + 1e4;
181
+ const owner = randomUUID();
182
+ const ownerPath = `${lock}/owner`;
183
+ let lease;
184
+ while (true) {
185
+ let created = false;
186
+ try {
187
+ await mkdir(lock, { mode: 448 });
188
+ created = true;
189
+ if (process.platform !== "win32") await applyMetadataPermissions(lock, permissions.mode & 504, permissions.gid);
190
+ const ownerFile = await open(ownerPath, "wx");
191
+ try {
192
+ await ownerFile.writeFile(owner);
193
+ } catch (error) {
194
+ await ownerFile.close();
195
+ throw error;
196
+ }
197
+ lease = ownerFile;
198
+ break;
199
+ } catch (error) {
200
+ if (created) {
201
+ try {
202
+ await removeOwnedGate(lock);
203
+ } catch (cleanupError) {
204
+ throw new AggregateError([error, cleanupError], "Workspace gate acquisition and cleanup failed", { cause: error });
205
+ }
206
+ throw error;
207
+ }
208
+ if (Reflect.get(Object(error), "code") !== "EEXIST") throw error;
209
+ await validateLockDirectory(lock);
210
+ if (Date.now() >= (deadline?.() ?? expiresAt)) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
211
+ else await setTimeout$1(25);
212
+ }
213
+ }
214
+ try {
215
+ return await withLeaseHeartbeat(lease, operation);
216
+ } finally {
217
+ await removeOwnedGate(lock);
218
+ }
219
+ }
220
+ async function withFilesystemReadLock(lock, permissions, description, operation, onFailure) {
221
+ const reader = `${lock}.readers/${randomUUID()}`;
222
+ await ensureLockDirectory(`${lock}.readers`);
223
+ if (process.platform !== "win32") await applyMetadataPermissions(`${lock}.readers`, permissions.mode & 504, permissions.gid);
224
+ const lease = await open(reader, "wx");
225
+ try {
226
+ return await withLeaseHeartbeat(lease, operation, onFailure);
227
+ } finally {
228
+ await rm(reader, { force: true });
229
+ await withFilesystemLock(`${lock}.gate`, permissions, description, async () => {
230
+ await rmdir(`${lock}.readers`).catch((error) => {
231
+ if (![
232
+ "ENOENT",
233
+ "ENOTEMPTY",
234
+ "EEXIST"
235
+ ].includes(error.code ?? "")) throw error;
236
+ });
237
+ }, () => Date.now()).catch(() => {});
238
+ }
239
+ }
240
+ async function withFilesystemWriteLock(lock, permissions, description, operation) {
241
+ return await withFilesystemLock(`${lock}.gate`, permissions, description, async () => {
242
+ const readers = `${lock}.readers`;
243
+ const deadline = Date.now() + 1e4;
244
+ while (true) {
245
+ await validateLockDirectory(readers);
246
+ if ((await readdir(readers).catch((error) => {
247
+ if (error.code === "ENOENT") return [];
248
+ throw error;
249
+ })).length === 0) {
250
+ await rmdir(readers).catch(() => {});
251
+ return await operation();
252
+ }
253
+ if (Date.now() >= deadline) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
254
+ await setTimeout$1(25);
255
+ }
256
+ });
257
+ }
258
+ async function withFilesystemWriterIntent(lock, permissions, operation) {
259
+ const intents = `${lock}.writers`;
260
+ const intent = `${intents}/${randomUUID()}`;
261
+ for (;;) try {
262
+ await ensureLockDirectory(intents);
263
+ if (process.platform !== "win32") await applyMetadataPermissions(intents, permissions.mode & 504, permissions.gid);
264
+ await mkdir(intent, { mode: 448 });
265
+ break;
266
+ } catch (error) {
267
+ if (Reflect.get(Object(error), "code") !== "ENOENT") {
268
+ await rmdir(intents).catch(() => {});
269
+ throw error;
270
+ }
271
+ }
272
+ try {
273
+ return await operation();
274
+ } finally {
275
+ await rm(intent, {
276
+ recursive: true,
277
+ force: true
278
+ });
279
+ await rmdir(intents).catch((error) => {
280
+ if (![
281
+ "ENOENT",
282
+ "ENOTEMPTY",
283
+ "EEXIST"
284
+ ].includes(error.code ?? "")) throw error;
285
+ });
286
+ }
287
+ }
288
+ const sharedReadLeases = /* @__PURE__ */ new Map();
289
+ const pendingWriters = /* @__PURE__ */ new Map();
290
+ async function openSharedReadLease(lock, permissions, description) {
291
+ let release;
292
+ const released = new Promise((resolve) => {
293
+ release = resolve;
294
+ });
295
+ let settled;
296
+ const acquired = new Promise((resolve, reject) => {
297
+ settled = withFilesystemReadLock(lock, permissions, description, async () => {
298
+ resolve();
299
+ await released;
300
+ }, (error) => {
301
+ lease.failure = { error };
302
+ });
303
+ settled.catch(reject);
304
+ });
305
+ const lease = {
306
+ acquired,
307
+ readers: 0,
308
+ release,
309
+ settled
310
+ };
311
+ settled.catch(() => {
312
+ if (sharedReadLeases.get(lock) === lease) sharedReadLeases.delete(lock);
313
+ });
314
+ await acquired;
315
+ return lease;
316
+ }
317
+ const readAdmissions = /* @__PURE__ */ new Map();
318
+ async function admitSharedReader(lock, permissions, description, deadline) {
319
+ const ticket = {
320
+ deadline,
321
+ charged: false
322
+ };
323
+ let admission = readAdmissions.get(lock);
324
+ if (!admission) {
325
+ admission = {
326
+ tickets: /* @__PURE__ */ new Set(),
327
+ admitted: Promise.resolve(void 0)
328
+ };
329
+ const batch = admission;
330
+ readAdmissions.set(lock, batch);
331
+ let chargedLease;
332
+ let chargedCount = 0;
333
+ const liveTickets = () => [...batch.tickets].filter((reader) => Date.now() < reader.deadline);
334
+ batch.admitted = withFilesystemLock(`${lock}.gate`, permissions, description, async () => {
335
+ readAdmissions.delete(lock);
336
+ if (!liveTickets().length) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
337
+ if (pendingWriters.has(lock) || await lstat(`${lock}.writers`).then(() => true).catch((error) => {
338
+ if (error.code === "ENOENT") return false;
339
+ throw error;
340
+ })) return void 0;
341
+ let lease = sharedReadLeases.get(lock);
342
+ if (!lease) {
343
+ lease = await openSharedReadLease(lock, permissions, description);
344
+ sharedReadLeases.set(lock, lease);
345
+ }
346
+ const tickets = liveTickets();
347
+ chargedCount = tickets.length;
348
+ if (!chargedCount) {
349
+ await releaseSharedReaders(lock, lease, 0);
350
+ throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
351
+ }
352
+ lease.readers += chargedCount;
353
+ chargedLease = lease;
354
+ for (const reader of tickets) reader.charged = true;
355
+ return lease;
356
+ }, () => Math.max(...[...batch.tickets].map((reader) => reader.deadline))).catch(async (error) => {
357
+ if (chargedLease) try {
358
+ await releaseSharedReaders(lock, chargedLease, chargedCount);
359
+ } catch (cleanupError) {
360
+ throw new AggregateError([error, cleanupError], "Workspace reader admission and cleanup failed", { cause: error });
361
+ }
362
+ throw error;
363
+ }).finally(() => {
364
+ if (readAdmissions.get(lock) === batch) readAdmissions.delete(lock);
365
+ });
366
+ }
367
+ admission.tickets.add(ticket);
368
+ const batch = admission;
369
+ let timedOut = false;
370
+ let timeout;
371
+ const expired = new Promise((_, reject) => {
372
+ timeout = setInterval(() => {
373
+ if (Date.now() < deadline) return;
374
+ timedOut = true;
375
+ batch.tickets.delete(ticket);
376
+ reject(workspaceError(`[vitehub] Timed out waiting to ${description}.`));
377
+ }, 25);
378
+ });
379
+ try {
380
+ const lease = await Promise.race([batch.admitted, expired]);
381
+ if (lease && !ticket.charged) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
382
+ return lease;
383
+ } catch (error) {
384
+ if (timedOut && ticket.charged) try {
385
+ await batch.admitted.then((lease) => lease ? releaseSharedReaders(lock, lease) : void 0, () => void 0);
386
+ } catch (cleanupError) {
387
+ throw new AggregateError([error, cleanupError], "Workspace reader timeout and cleanup failed", { cause: error });
388
+ }
389
+ throw error;
390
+ } finally {
391
+ clearInterval(timeout);
392
+ batch.tickets.delete(ticket);
393
+ }
394
+ }
395
+ async function releaseSharedReaders(lock, lease, count = 1) {
396
+ lease.readers -= count;
397
+ if (lease.readers === 0) {
398
+ if (sharedReadLeases.get(lock) === lease) sharedReadLeases.delete(lock);
399
+ lease.release();
400
+ await lease.settled;
401
+ }
402
+ if (lease.failure) throw lease.failure.error;
403
+ }
404
+ async function withSharedFilesystemReadLock(lock, permissions, description, operation) {
405
+ const deadline = Date.now() + 1e4;
406
+ let lease;
407
+ while (!lease) {
408
+ for (let writers = pendingWriters.get(lock); writers; writers = pendingWriters.get(lock)) {
409
+ const remaining = deadline - Date.now();
410
+ if (remaining <= 0) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
411
+ await new Promise((resolve, reject) => {
412
+ const timeout = setTimeout(() => reject(workspaceError(`[vitehub] Timed out waiting to ${description}.`)), remaining);
413
+ writers.idle.then(() => {
414
+ clearTimeout(timeout);
415
+ resolve();
416
+ });
417
+ });
418
+ }
419
+ const writerIntent = await lstat(`${lock}.writers`).catch((error) => {
420
+ if (error.code === "ENOENT") return void 0;
421
+ throw error;
422
+ });
423
+ const gate = await lstat(`${lock}.gate`).catch((error) => {
424
+ if (error.code === "ENOENT") return void 0;
425
+ throw error;
426
+ });
427
+ if (!writerIntent && !gate && !pendingWriters.has(lock)) {
428
+ lease = await admitSharedReader(lock, permissions, description, deadline);
429
+ if (lease) break;
430
+ }
431
+ if (writerIntent) await validateLockDirectory(`${lock}.writers`);
432
+ if (gate) await validateLockDirectory(`${lock}.gate`);
433
+ if (Date.now() >= deadline) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
434
+ await setTimeout$1(25);
435
+ }
436
+ try {
437
+ await lease.acquired;
438
+ if (Date.now() >= deadline) throw workspaceError(`[vitehub] Timed out waiting to ${description}.`);
439
+ if (lease.failure) throw lease.failure.error;
440
+ return await operation();
441
+ } finally {
442
+ await releaseSharedReaders(lock, lease);
443
+ }
444
+ }
445
+ async function withPendingWriter(lock, operation) {
446
+ let writers = pendingWriters.get(lock);
447
+ if (!writers) {
448
+ let resolve;
449
+ writers = {
450
+ count: 0,
451
+ idle: new Promise((done) => {
452
+ resolve = done;
453
+ }),
454
+ resolve
455
+ };
456
+ pendingWriters.set(lock, writers);
457
+ }
458
+ writers.count++;
459
+ try {
460
+ return await operation();
461
+ } finally {
462
+ if (--writers.count === 0) {
463
+ pendingWriters.delete(lock);
464
+ writers.resolve();
465
+ }
466
+ }
467
+ }
468
+ async function withWorkspacePathLock(root, path, operation, readOnly = false, heldReadPrefix) {
469
+ const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
470
+ const paths = parts.map((_, index) => parts.slice(0, index + 1).join("/"));
471
+ if (paths.length === 0) return await operation();
472
+ await mkdir(root, { recursive: true });
473
+ const permissions = await stat(root);
474
+ for (const directory of [`${root}/.vitehub`, `${root}/.vitehub/locks`]) {
475
+ await ensureLockDirectory(directory);
476
+ if (process.platform !== "win32") await applyMetadataPermissions(directory, permissions.mode & 504, permissions.gid);
477
+ }
478
+ const lock = async (index) => {
479
+ if (index === paths.length) return await operation();
480
+ const lockedPath = paths[index];
481
+ if (readOnly && heldReadPrefix && (heldReadPrefix === lockedPath || heldReadPrefix.startsWith(`${lockedPath}/`))) return await lock(index + 1);
482
+ const lockPath = `${root}/.vitehub/locks/${createHash("sha256").update(lockedPath).digest("hex")}`;
483
+ const next = () => lock(index + 1);
484
+ const description = `${readOnly ? "read" : "write"} Workspace path: ${lockedPath}`;
485
+ return !readOnly && index === paths.length - 1 ? await withPendingWriter(lockPath, () => withFilesystemWriterIntent(lockPath, permissions, () => withFilesystemWriteLock(lockPath, permissions, description, next))) : await withSharedFilesystemReadLock(lockPath, permissions, description, next);
486
+ };
487
+ return await lock(0);
488
+ }
489
+ function isGitMetadataName(name) {
490
+ return name === ".git" || process.platform === "win32" && name.toLowerCase() === ".git";
491
+ }
492
+ /** Check whether a path belongs to a Git worktree before classifying Git errors. */
493
+ async function hasGitMetadata(root) {
494
+ let current = resolve(root);
495
+ while (true) {
496
+ if (await lstat(join(current, ".git")).catch((error) => {
497
+ if (error.code === "ENOENT") return void 0;
498
+ throw error;
499
+ })) return true;
500
+ const parent = resolve(current, "..");
501
+ if (parent === current) return false;
502
+ current = parent;
503
+ }
504
+ }
505
+ /** Paths that Git ignores under a checkout root. Ignored directories are listed once, not descended. */
506
+ async function gitIgnoredWorkspacePaths(root) {
507
+ const { execFile } = await import("node:child_process");
508
+ const gitMetadata = await hasGitMetadata(root);
509
+ return [".git", ...(await new Promise((resolveOutput, reject) => execFile("git", [
510
+ "-C",
511
+ root,
512
+ "-c",
513
+ "core.hooksPath=/dev/null",
514
+ "ls-files",
515
+ "-z",
516
+ "--others",
517
+ "--ignored",
518
+ "--exclude-standard",
519
+ "--directory"
520
+ ], {
521
+ encoding: "utf8",
522
+ env: {
523
+ ...process.env,
524
+ GIT_TERMINAL_PROMPT: "0",
525
+ LC_ALL: "C"
526
+ },
527
+ maxBuffer: 67108864
528
+ }, (error, stdout, stderr) => {
529
+ if (error) {
530
+ if (Reflect.get(Object(error), "code") === 128 && /not a git repository/i.test(stderr) && !gitMetadata) {
531
+ resolveOutput("");
532
+ return;
533
+ }
534
+ reject(error);
535
+ return;
536
+ }
537
+ resolveOutput(stdout);
538
+ }))).split("\0").filter(Boolean).map((path) => path.replace(/\/$/, ""))];
539
+ }
540
+ /** Include ignore rules from Git roots that contain a non-root listing prefix. */
541
+ async function gitIgnoredWorkspacePathsForPrefix(root, current, excluded) {
542
+ const { relative, sep } = await import("node:path");
543
+ const relativePrefix = relative(root, current);
544
+ if (!relativePrefix || relativePrefix === "." || relativePrefix.startsWith(`..${sep}`)) return [...excluded];
545
+ const result = [...excluded];
546
+ let ancestor = root;
547
+ let prefix = "";
548
+ for (const segment of relativePrefix.split(sep)) {
549
+ ancestor = `${ancestor}/${segment}`;
550
+ prefix = prefix ? `${prefix}/${segment}` : segment;
551
+ if ((await readdir(ancestor, { withFileTypes: true }).catch(() => [])).some((dirent) => isGitMetadataName(dirent.name))) {
552
+ const nestedExcluded = await gitIgnoredWorkspacePaths(ancestor);
553
+ result.push(...nestedExcluded.map((path) => `${prefix}/${path}`));
554
+ }
555
+ }
556
+ return result;
557
+ }
558
+ const processPathLocks = /* @__PURE__ */ new Map();
559
+ const processMetadataRoots = /* @__PURE__ */ new Map();
560
+ async function withProcessLock(key, exclusive, operation) {
561
+ let state = processPathLocks.get(key);
562
+ if (!state) processPathLocks.set(key, state = {
563
+ pendingWriters: 0,
564
+ readers: 0,
565
+ writer: false,
566
+ waiters: []
567
+ });
568
+ const current = state;
569
+ if (exclusive) current.pendingWriters++;
570
+ try {
571
+ while (current.writer || (exclusive ? current.readers > 0 : current.pendingWriters > 0)) await new Promise((resolve) => current.waiters.push(resolve));
572
+ } finally {
573
+ if (exclusive) current.pendingWriters--;
574
+ }
575
+ if (exclusive) current.writer = true;
576
+ else current.readers++;
577
+ try {
578
+ return await operation();
579
+ } finally {
580
+ if (exclusive) current.writer = false;
581
+ else current.readers--;
582
+ const waiters = current.waiters.splice(0);
583
+ if (!current.writer && current.readers === 0 && current.pendingWriters === 0 && waiters.length === 0) processPathLocks.delete(key);
584
+ for (const resolve of waiters) resolve();
585
+ }
586
+ }
587
+ async function prepareProcessMetadataRoot(root) {
588
+ const { lstat, mkdir, stat } = await import("node:fs/promises");
589
+ const previous = processMetadataRoots.get(root);
590
+ if (previous) {
591
+ if (await previous.then(() => lstat(`${root}/.vitehub`).then(() => true, () => false), () => false)) return;
592
+ if (processMetadataRoots.get(root) === previous) processMetadataRoots.delete(root);
593
+ }
594
+ let prepared = processMetadataRoots.get(root);
595
+ if (!prepared) {
596
+ prepared = (async () => {
597
+ await mkdir(root, { recursive: true });
598
+ const permissions = await stat(root);
599
+ await ensureLockDirectory(`${root}/.vitehub`);
600
+ if (process.platform !== "win32") await applyMetadataPermissions(`${root}/.vitehub`, permissions.mode & 504, permissions.gid);
601
+ })();
602
+ processMetadataRoots.set(root, prepared);
603
+ const current = prepared;
604
+ current.catch(() => {
605
+ if (processMetadataRoots.get(root) === current) processMetadataRoots.delete(root);
606
+ });
607
+ }
608
+ await prepared;
609
+ }
610
+ /**
611
+ * Keeps the lock order of withWorkspacePathLock in memory: shared reads on
612
+ * each parent path and an exclusive lock on the target path for a write. Use
613
+ * it only for a store root that one process owns.
614
+ */
615
+ async function withProcessPathLock(root, path, operation, readOnly = false) {
616
+ const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
617
+ const paths = parts.map((_, index) => parts.slice(0, index + 1).join("/"));
618
+ if (paths.length === 0) return await operation();
619
+ const key = resolve(root);
620
+ await prepareProcessMetadataRoot(key);
621
+ const lock = async (index) => {
622
+ if (index === paths.length) return await operation();
623
+ return await withProcessLock(`${key}\0${paths[index]}`, !readOnly && index === paths.length - 1, () => lock(index + 1));
624
+ };
625
+ return await lock(0);
626
+ }
627
+ async function walk(root, current, privatePaths, excluded = [], recursive = true) {
628
+ const { isAbsolute, relative, sep } = await import("node:path");
629
+ if (privatePaths.some((path) => {
630
+ const relativePath = relative(path, current);
631
+ return !relativePath || !isAbsolute(relativePath) && relativePath !== ".." && !relativePath.startsWith(`..${sep}`);
632
+ })) return [];
633
+ const entries = [];
634
+ const dirents = await readdir(current, { withFileTypes: true }).catch((error) => {
635
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return [];
636
+ throw error;
637
+ });
638
+ let currentExcluded = excluded;
639
+ if (current !== root && dirents.some((dirent) => isGitMetadataName(dirent.name))) {
640
+ const nestedExcluded = await gitIgnoredWorkspacePaths(current);
641
+ const prefix = normalizeWorkspacePath(relative(root, current));
642
+ currentExcluded = [...excluded, ...nestedExcluded.map((path) => prefix ? `${prefix}/${path}` : path)];
643
+ }
644
+ for (const dirent of dirents) {
645
+ if (dirent.isSymbolicLink()) continue;
646
+ const absolute = `${current}/${dirent.name}`;
647
+ if (privatePaths.some((path) => !relative(path, absolute))) continue;
648
+ const path = normalizeWorkspacePath(relative(root, absolute));
649
+ if (path.split("/")[0]?.toLowerCase() === ".vitehub") continue;
650
+ if (path.split("/").some((component) => isGitMetadataName(component))) continue;
651
+ if (isExcludedWorkspacePath(path, currentExcluded)) continue;
652
+ const info = await stat(absolute).catch((error) => {
653
+ if (error.code === "ENOENT") return void 0;
654
+ throw error;
655
+ });
656
+ if (!info) continue;
657
+ if (dirent.isDirectory()) {
658
+ entries.push({
659
+ path,
660
+ type: "directory",
661
+ mtime: info.mtimeMs
662
+ });
663
+ if (recursive) entries.push(...await walk(root, absolute, privatePaths, currentExcluded, true));
664
+ continue;
665
+ }
666
+ if (dirent.isFile()) {
667
+ const entry = {
668
+ path,
669
+ type: "file",
670
+ size: info.size,
671
+ mtime: info.mtimeMs
672
+ };
673
+ entries.push(entry);
674
+ }
675
+ }
676
+ return entries;
677
+ }
678
+ async function fileDigest(path) {
679
+ return await new Promise((resolve, reject) => {
680
+ const hash = createHash("sha256");
681
+ const stream = createReadStream(path);
682
+ stream.on("data", (chunk) => hash.update(chunk));
683
+ stream.on("error", reject);
684
+ stream.on("end", () => resolve(hash.digest("hex")));
685
+ });
686
+ }
687
+ var LocalWorkspaceStore = class {
688
+ root;
689
+ [workspaceStoreTarget]() {
690
+ return {
691
+ provider: "local",
692
+ containsPath: async (ancestor, path) => {
693
+ const readIdentity = async (value) => await stat(value, { bigint: true }).catch((error) => {
694
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return void 0;
695
+ throw error;
696
+ });
697
+ const destination = await readIdentity(resolveInside(this.root, ancestor));
698
+ if (!destination) return false;
699
+ const root = resolve(this.root);
700
+ let current = resolveInside(root, path);
701
+ while (current !== root) {
702
+ const source = await readIdentity(current);
703
+ if (source && source.dev === destination.dev && source.ino === destination.ino) return true;
704
+ current = dirname(current);
705
+ }
706
+ return false;
707
+ }
708
+ };
709
+ }
710
+ #baseline;
711
+ #files = /* @__PURE__ */ new Map();
712
+ #metaCache;
713
+ #fileMetadataRoot;
714
+ #metaPath;
715
+ #ignoreGit;
716
+ #processLocks;
717
+ constructor(root, options = {}) {
718
+ this.root = root;
719
+ this.#ignoreGit = options.ignore === "git";
720
+ this.#processLocks = options.locks === "process";
721
+ this.#fileMetadataRoot = `${root}/.vitehub/file-metadata`;
722
+ this.#metaPath = `${root}.meta.json`;
723
+ }
724
+ async #pathLock(root, path, operation, readOnly = false) {
725
+ return this.#processLocks ? await withProcessPathLock(root, path, operation, readOnly) : await withWorkspacePathLock(root, path, operation, readOnly);
726
+ }
727
+ #removalMarker(path) {
728
+ return `${this.root}/.vitehub/file-removals/${createHash("sha256").update(path).digest("hex")}`;
729
+ }
730
+ async #assertNoPendingRemoval(path) {
731
+ const directory = `${this.root}/.vitehub/file-removals`;
732
+ const info = await lstat(directory).catch((error) => {
733
+ if (error.code === "ENOENT") return void 0;
734
+ throw error;
735
+ });
736
+ if (!info) return;
737
+ assertTrustedMetadata(directory, info, await stat(this.root));
738
+ if (!info.isDirectory()) throw workspaceError(`[vitehub] Invalid Workspace removal directory.`);
739
+ const parts = normalizeWorkspacePath(path).split("/").filter(Boolean);
740
+ for (let index = 0; index <= parts.length; index++) {
741
+ const ancestor = parts.slice(0, index).join("/");
742
+ if (await lstat(this.#removalMarker(ancestor)).catch((error) => {
743
+ if (error.code === "ENOENT") return void 0;
744
+ throw error;
745
+ })) throw workspaceError(`[vitehub] Interrupted Workspace removal at ${ancestor || "/"}; retry removal before accessing ${path}.`);
746
+ }
747
+ }
748
+ async #readFileMetadata(path) {
749
+ await this.#assertNoPendingRemoval(path);
750
+ const { root } = await this.#prepareMetadataDirectories(path, false, false);
751
+ if (!root) return;
752
+ const metadataPath = resolveInside(this.#fileMetadataRoot, `${path}/metadata.json`);
753
+ const info = await lstat(metadataPath).catch((error) => {
754
+ if (error.code === "ENOENT") return void 0;
755
+ throw error;
756
+ });
757
+ if (info) {
758
+ assertTrustedMetadata(metadataPath, info, root);
759
+ if (!info.isFile()) return;
760
+ }
761
+ const file = await open(metadataPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)).catch((error) => {
762
+ if (error.code === "ENOENT") return void 0;
763
+ throw error;
764
+ });
765
+ if (!file) {
766
+ this.#files.delete(path);
767
+ return;
768
+ }
769
+ let content;
770
+ try {
771
+ const opened = await file.stat();
772
+ assertTrustedMetadata(metadataPath, opened, root);
773
+ if (!opened.isFile()) return;
774
+ content = await file.readFile("utf8");
775
+ } finally {
776
+ await file.close();
777
+ }
778
+ let value;
779
+ try {
780
+ value = JSON.parse(content);
781
+ } catch {
782
+ throw workspaceError(`[vitehub] Invalid Workspace metadata for ${path}.`);
783
+ }
784
+ const parsed = safeParse(object({
785
+ path: literal(path),
786
+ mediaType: fallback(optional(string()), void 0),
787
+ metadata: fileMetadataSchema
788
+ }), value);
789
+ if (!parsed.success) throw workspaceError(`[vitehub] Invalid Workspace metadata for ${path}.`);
790
+ const { path: _path, ...result } = parsed.output;
791
+ return {
792
+ ...result,
793
+ metadata: assertFileMetadata(path, result.metadata)
794
+ };
795
+ }
796
+ async #prepareMetadataDirectories(path, create, repair = true) {
797
+ const root = await stat(this.root).catch((error) => {
798
+ if (error.code === "ENOENT" && !create) return void 0;
799
+ throw error;
800
+ });
801
+ if (!root) return {
802
+ mode: 384,
803
+ gid: void 0,
804
+ root: void 0
805
+ };
806
+ const mode = root.mode & 504;
807
+ let directory = this.root;
808
+ for (const part of [
809
+ ".vitehub",
810
+ "file-metadata",
811
+ ...normalizeWorkspacePath(path).split("/").filter(Boolean)
812
+ ]) {
813
+ if (part) directory = resolveInside(directory, part);
814
+ if (create) await mkdir(directory, { mode: 448 }).catch((error) => {
815
+ if (error.code !== "EEXIST") throw error;
816
+ });
817
+ const info = await lstat(directory).catch((error) => {
818
+ if (error.code === "ENOENT" && !create) return void 0;
819
+ throw error;
820
+ });
821
+ if (!info) return {
822
+ mode: mode & 438,
823
+ gid: root.gid,
824
+ root: void 0
825
+ };
826
+ assertTrustedMetadata(directory, info, root);
827
+ if (!info.isDirectory()) {
828
+ if (repair) await rm(directory, { force: true });
829
+ if (!create) return {
830
+ mode: mode & 438,
831
+ gid: root.gid,
832
+ root: void 0
833
+ };
834
+ await mkdir(directory, { mode: 448 });
835
+ }
836
+ if (repair && process.platform !== "win32") await applyMetadataPermissions(directory, mode, root.gid);
837
+ }
838
+ return {
839
+ mode: mode & 438,
840
+ gid: root.gid,
841
+ root
842
+ };
843
+ }
844
+ async #writeFileMetadata(path, value) {
845
+ await this.#assertNoPendingRemoval(path);
846
+ const metadataPath = resolveInside(this.#fileMetadataRoot, `${path}/metadata.json`);
847
+ const hasMetadata = value.mediaType !== void 0 || value.metadata !== void 0;
848
+ const permissions = await this.#prepareMetadataDirectories(path, hasMetadata);
849
+ if (!permissions.root) {
850
+ this.#files.delete(path);
851
+ return;
852
+ }
853
+ const existing = await lstat(metadataPath).catch((error) => {
854
+ if (error.code === "ENOENT") return void 0;
855
+ throw error;
856
+ });
857
+ if (existing) {
858
+ assertTrustedMetadata(metadataPath, existing, permissions.root);
859
+ if (existing.isDirectory()) await rm(metadataPath, {
860
+ recursive: true,
861
+ force: true
862
+ });
863
+ }
864
+ if (!hasMetadata) {
865
+ await rm(metadataPath, { force: true });
866
+ this.#files.delete(path);
867
+ return;
868
+ }
869
+ const temp = `${metadataPath}.${randomUUID()}.tmp`;
870
+ try {
871
+ await writeFile(temp, JSON.stringify({
872
+ path,
873
+ ...value
874
+ }), { mode: 384 });
875
+ if (process.platform !== "win32" && permissions.gid !== void 0) await applyMetadataPermissions(temp, permissions.mode, permissions.gid);
876
+ await rename(temp, metadataPath);
877
+ } catch (error) {
878
+ await rm(temp, { force: true }).catch(() => void 0);
879
+ throw error;
880
+ }
881
+ this.#files.delete(path);
882
+ }
883
+ async readFile(path) {
884
+ return await this.#pathLock(this.root, path, () => this.#readFile(path), true);
885
+ }
886
+ async #readFile(path) {
887
+ const absolute = resolveInside(this.root, path);
888
+ await this.#assertPathComponents(path);
889
+ const bytes = await readFile(absolute).catch((error) => {
890
+ if (error.code === "ENOENT") return void 0;
891
+ throw error;
892
+ });
893
+ if (!bytes) return void 0;
894
+ const normalized = normalizeWorkspacePath(path);
895
+ const metadata = await this.#readFileMetadata(normalized);
896
+ return {
897
+ path: normalized,
898
+ content: new Uint8Array(bytes),
899
+ mediaType: metadata?.mediaType,
900
+ metadata: metadata?.metadata
901
+ };
902
+ }
903
+ async writeFile(path, file) {
904
+ await this.#pathLock(this.root, path, () => this.#writeFile(path, file));
905
+ }
906
+ async writeFileConditional(path, file, ifDigest) {
907
+ await this.#pathLock(this.root, path, async () => {
908
+ const normalized = normalizeWorkspacePath(path);
909
+ const current = await this.#stat(normalized);
910
+ assertWorkspaceDigest(normalized, ifDigest, current?.type === "file" ? current.digest : void 0);
911
+ await this.#writeFile(normalized, file);
912
+ });
913
+ }
914
+ async #writeFile(path, file) {
915
+ file = {
916
+ ...file,
917
+ metadata: assertFileMetadata(path, file.metadata)
918
+ };
919
+ const { dirname } = await import("node:path");
920
+ const absolute = resolveInside(this.root, path);
921
+ const tempRoot = `${this.root}/.vitehub/tmp`;
922
+ const temp = `${tempRoot}/${randomUUID()}.tmp`;
923
+ const backup = `${tempRoot}/${randomUUID()}.bak`;
924
+ await reclaimCommittedBackups(tempRoot);
925
+ const normalized = normalizeWorkspacePath(path);
926
+ await this.#assertPathComponents(normalized);
927
+ const bytes = contentToBytes(file.content);
928
+ const digest = await sha256(bytes);
929
+ const existing = await this.#stat(normalized);
930
+ if (existing?.type === "directory") throw workspaceError(`[vitehub] Cannot write a file over directory: ${normalized}.`);
931
+ if (existing?.type === "file" && existing.digest === digest) {
932
+ await this.#writeFileMetadata(normalized, {
933
+ mediaType: file.mediaType,
934
+ metadata: file.metadata
935
+ });
936
+ return;
937
+ }
938
+ await Promise.all([mkdir(dirname(absolute), { recursive: true }), mkdir(tempRoot, { recursive: true })]);
939
+ try {
940
+ await writeFile(temp, bytes);
941
+ const hadExisting = existing?.type === "file";
942
+ await this.#publishFile({
943
+ absolute,
944
+ normalized,
945
+ temp,
946
+ backup,
947
+ hadExisting,
948
+ file
949
+ });
950
+ return;
951
+ } catch (error) {
952
+ await rm(temp, { force: true }).catch(() => void 0);
953
+ throw error;
954
+ }
955
+ }
956
+ async #publishFile({ absolute, normalized, temp, backup, hadExisting, file }) {
957
+ const foreignUid = hadExisting ? await backupFile(absolute, backup) : void 0;
958
+ await rename(temp, absolute).catch(async (error) => {
959
+ await rm(backup, { force: true });
960
+ throw error;
961
+ });
962
+ try {
963
+ await this.#writeFileMetadata(normalized, {
964
+ mediaType: file.mediaType,
965
+ metadata: file.metadata
966
+ });
967
+ } catch (error) {
968
+ if (hadExisting) await restoreBackup(backup, absolute, foreignUid, error);
969
+ else await rm(absolute, { force: true });
970
+ throw error;
971
+ }
972
+ await reclaimBackup(backup);
973
+ }
974
+ async #assertPathComponents(path, includeTarget = true) {
975
+ const root = resolve(this.root);
976
+ const parts = relative(root, resolveInside(root, path)).split(sep).filter(Boolean);
977
+ if (!includeTarget) parts.pop();
978
+ let current = root;
979
+ for (const part of parts) {
980
+ current = join(current, part);
981
+ const info = await lstat(current).catch((error) => {
982
+ if (error.code === "ENOENT") return void 0;
983
+ throw error;
984
+ });
985
+ if (!info) return;
986
+ if (info.isSymbolicLink()) throw workspaceError(`[vitehub] Refusing to access symbolic-link Workspace path: ${path}.`);
987
+ }
988
+ }
989
+ async writeFileStream(path, file) {
990
+ return await this.#pathLock(this.root, path, () => this.#writeFileStream(path, file));
991
+ }
992
+ async #writeFileStream(path, file) {
993
+ await this.#assertPathComponents(path);
994
+ file = {
995
+ ...file,
996
+ metadata: assertFileMetadata(path, file.metadata)
997
+ };
998
+ const { dirname } = await import("node:path");
999
+ const normalized = normalizeWorkspacePath(path);
1000
+ const absolute = resolveInside(this.root, path);
1001
+ const tempRoot = `${this.root}/.vitehub/tmp`;
1002
+ const temp = `${tempRoot}/${randomUUID()}.tmp`;
1003
+ const backup = `${tempRoot}/${randomUUID()}.bak`;
1004
+ await reclaimCommittedBackups(tempRoot);
1005
+ const hash = createHash("sha256");
1006
+ let size = 0;
1007
+ await Promise.all([mkdir(dirname(absolute), { recursive: true }), mkdir(tempRoot, { recursive: true })]);
1008
+ try {
1009
+ const hashing = new Transform({ transform(chunk, _encoding, callback) {
1010
+ hash.update(chunk);
1011
+ size += chunk.byteLength;
1012
+ callback(void 0, chunk);
1013
+ } });
1014
+ await pipeline(Readable.from(contentStreamChunks(file.content)), hashing, createWriteStream(temp));
1015
+ const digest = hash.digest("hex");
1016
+ const existing = await this.#stat(normalized);
1017
+ if (existing?.type === "directory") throw workspaceError(`[vitehub] Cannot write a file over directory: ${normalized}.`);
1018
+ if (existing?.type === "file" && existing.digest === digest) {
1019
+ await rm(temp, { force: true });
1020
+ await this.#writeFileMetadata(normalized, {
1021
+ mediaType: file.mediaType,
1022
+ metadata: file.metadata
1023
+ });
1024
+ return {
1025
+ ...existing,
1026
+ mediaType: file.mediaType,
1027
+ metadata: file.metadata,
1028
+ size,
1029
+ digest
1030
+ };
1031
+ }
1032
+ const hadExisting = existing?.type === "file";
1033
+ await this.#publishFile({
1034
+ absolute,
1035
+ normalized,
1036
+ temp,
1037
+ backup,
1038
+ hadExisting,
1039
+ file
1040
+ });
1041
+ return {
1042
+ path: normalized,
1043
+ type: "file",
1044
+ size,
1045
+ mediaType: file.mediaType,
1046
+ metadata: file.metadata,
1047
+ digest
1048
+ };
1049
+ } catch (error) {
1050
+ await rm(temp, { force: true }).catch(() => void 0);
1051
+ throw error;
1052
+ }
1053
+ }
1054
+ async list(prefix = "", options = {}) {
1055
+ return await this.#list(prefix, options, false);
1056
+ }
1057
+ async #list(prefix, options, includeDigest) {
1058
+ await this.#assertPathComponents(prefix);
1059
+ const normalizedPrefix = normalizeWorkspacePath(prefix);
1060
+ const current = normalizedPrefix ? resolveInside(this.root, normalizedPrefix) : this.root;
1061
+ const privatePaths = [this.#fileMetadataRoot, this.#metaPath];
1062
+ let excluded = this.#ignoreGit ? [...options.exclude ?? [], ...await gitIgnoredWorkspacePaths(this.root)] : options.exclude;
1063
+ if (this.#ignoreGit) excluded = await gitIgnoredWorkspacePathsForPrefix(this.root, current, excluded ?? []);
1064
+ const filtered = (await walk(this.root, current, privatePaths, excluded, options.recursive === true)).filter((entry) => {
1065
+ if (!normalizedPrefix) return options.recursive || !entry.path.includes("/");
1066
+ if (entry.path === normalizedPrefix) return false;
1067
+ if (!entry.path.startsWith(`${normalizedPrefix}/`)) return false;
1068
+ return options.recursive || !entry.path.slice(normalizedPrefix.length + 1).includes("/");
1069
+ });
1070
+ const entries = [];
1071
+ const readBatchDurationMs = 1e3;
1072
+ const groups = /* @__PURE__ */ new Map();
1073
+ for (const entry of filtered) {
1074
+ const key = entry.path.split("/")[0];
1075
+ const group = groups.get(key) ?? [];
1076
+ group.push(entry);
1077
+ groups.set(key, group);
1078
+ }
1079
+ const independent = this.#processLocks ? filtered.map((entry) => [entry]) : [...groups.values()];
1080
+ for (let index = 0; index < independent.length; index += 64) await Promise.all(independent.slice(index, index + 64).map(async (group) => {
1081
+ if (this.#processLocks) {
1082
+ for (const entry of group) {
1083
+ const info = await this.#pathLock(this.root, entry.path, () => this.#stat(entry.path, includeDigest), true);
1084
+ if (info) entries.push(info);
1085
+ }
1086
+ return;
1087
+ }
1088
+ const heldReadPrefix = normalizedPrefix || group[0].path.split("/")[0];
1089
+ let offset = 0;
1090
+ while (offset < group.length) await withWorkspacePathLock(this.root, heldReadPrefix, async () => {
1091
+ const startedAt = Date.now();
1092
+ do {
1093
+ const entry = group[offset++];
1094
+ const info = await withWorkspacePathLock(this.root, entry.path, () => this.#stat(entry.path, includeDigest), true, heldReadPrefix);
1095
+ if (info) entries.push(info);
1096
+ } while (offset < group.length && Date.now() - startedAt < readBatchDurationMs);
1097
+ }, true);
1098
+ }));
1099
+ return entries.sort((a, b) => a.path.localeCompare(b.path));
1100
+ }
1101
+ async glob(pattern, options = {}) {
1102
+ const { cwd, matches } = createWorkspaceGlobMatcher(pattern, options);
1103
+ return (await this.list(cwd, { recursive: true })).filter((entry) => entry.type === "file" && matches(entry.path));
1104
+ }
1105
+ async stat(path) {
1106
+ return await this.#pathLock(this.root, path, () => this.#stat(path), true);
1107
+ }
1108
+ async #stat(path, includeDigest = true) {
1109
+ const normalized = normalizeWorkspacePath(path);
1110
+ const absolute = resolveInside(this.root, normalized);
1111
+ await this.#assertPathComponents(normalized);
1112
+ const info = await stat(absolute, { bigint: true }).catch((error) => {
1113
+ if (error.code === "ENOENT") return void 0;
1114
+ throw error;
1115
+ });
1116
+ if (!info) return void 0;
1117
+ const metadata = info.isFile() ? await this.#readFileMetadata(normalized) : void 0;
1118
+ const entry = {
1119
+ path: normalized,
1120
+ type: info.isDirectory() ? "directory" : "file",
1121
+ size: info.isFile() ? Number(info.size) : void 0,
1122
+ mtime: Number(info.mtimeNs) / 1e6,
1123
+ revision: info.isFile() ? `${info.dev}:${info.ino}:${info.birthtimeNs}:${info.ctimeNs}:${info.mtimeNs}` : void 0,
1124
+ mediaType: metadata?.mediaType,
1125
+ metadata: metadata?.metadata
1126
+ };
1127
+ if (includeDigest && info.isFile()) entry.digest = await fileDigest(absolute);
1128
+ return entry;
1129
+ }
1130
+ async mkdir(path, options = {}) {
1131
+ await this.#pathLock(this.root, path, async () => {
1132
+ await this.#assertPathComponents(path);
1133
+ await mkdir(resolveInside(this.root, path), { recursive: options.recursive ?? true });
1134
+ });
1135
+ }
1136
+ async removeEmptyDirectory(path) {
1137
+ await this.#pathLock(this.root, path, async () => {
1138
+ if (!normalizeWorkspacePath(path)) return;
1139
+ await this.#assertPathComponents(path, false);
1140
+ const absolute = resolveInside(this.root, path);
1141
+ const info = await lstat(absolute).catch((error) => {
1142
+ if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
1143
+ });
1144
+ if (!info || info.isSymbolicLink()) return;
1145
+ await rmdir(absolute).catch((error) => {
1146
+ if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
1147
+ });
1148
+ });
1149
+ }
1150
+ async rm(path, options = {}) {
1151
+ await this.#pathLock(this.root, path, () => this.#rm(path, options));
1152
+ }
1153
+ async #rm(path, options = {}) {
1154
+ await this.#assertPathComponents(path, false);
1155
+ const normalized = normalizeWorkspacePath(path);
1156
+ if (options.ifDigest !== void 0) {
1157
+ const current = await this.#stat(normalized);
1158
+ if (options.ifDigest === null ? current !== void 0 : current?.digest !== options.ifDigest) throw workspaceConflictError(path, options.ifDigest, current?.digest);
1159
+ }
1160
+ const metadata = await this.#prepareMetadataDirectories(normalized, false);
1161
+ const marker = this.#removalMarker(normalized);
1162
+ let createdMarker = false;
1163
+ if (metadata.root) {
1164
+ const directory = `${this.root}/.vitehub/file-removals`;
1165
+ await mkdir(directory, { mode: 448 }).catch((error) => {
1166
+ if (error.code !== "EEXIST") throw error;
1167
+ });
1168
+ const info = await lstat(directory);
1169
+ assertTrustedMetadata(directory, info, metadata.root);
1170
+ if (!info.isDirectory()) throw workspaceError(`[vitehub] Invalid Workspace removal directory.`);
1171
+ if (process.platform !== "win32") await applyMetadataPermissions(directory, metadata.root.mode & 504, metadata.root.gid);
1172
+ const file = await open(marker, "wx", 384).catch((error) => {
1173
+ if (error.code === "EEXIST") return void 0;
1174
+ throw error;
1175
+ });
1176
+ createdMarker = file !== void 0;
1177
+ await file?.close();
1178
+ }
1179
+ let missingTargetError;
1180
+ await rm(resolveInside(this.root, path), {
1181
+ recursive: options.recursive ?? false,
1182
+ force: options.force ?? false
1183
+ }).catch(async (error) => {
1184
+ if (error.code === "ERR_FS_EISDIR" && !options.recursive) {
1185
+ await rmdir(resolveInside(this.root, path));
1186
+ return;
1187
+ }
1188
+ throw error;
1189
+ }).catch(async (error) => {
1190
+ if (error.code === "ENOENT") {
1191
+ if (!options.force) missingTargetError = error;
1192
+ return;
1193
+ }
1194
+ if (createdMarker && !options.recursive) await rm(marker, { force: true });
1195
+ throw error;
1196
+ });
1197
+ for (const key of this.#files.keys()) if (key === normalized || key.startsWith(`${normalized}/`)) this.#files.delete(key);
1198
+ if (metadata.root) await rm(resolveInside(this.#fileMetadataRoot, normalized), {
1199
+ force: true,
1200
+ recursive: true
1201
+ });
1202
+ await rm(marker, { force: true });
1203
+ if (missingTargetError) throw missingTargetError;
1204
+ }
1205
+ async snapshot(options = {}) {
1206
+ await mkdir(this.root, { recursive: true });
1207
+ const snapshot = await this.#createSnapshot(options.name);
1208
+ this.#baseline = snapshot;
1209
+ return snapshot;
1210
+ }
1211
+ async diff(options = {}) {
1212
+ const from = options.from || this.#baseline;
1213
+ const to = await this.#createSnapshot();
1214
+ const entries = [];
1215
+ const keys = /* @__PURE__ */ new Set([...Object.keys(from?.entries || {}), ...Object.keys(to.entries)]);
1216
+ for (const path of [...keys].sort()) {
1217
+ const before = from && Object.hasOwn(from.entries, path) ? from.entries[path] : void 0;
1218
+ const after = Object.hasOwn(to.entries, path) ? to.entries[path] : void 0;
1219
+ if (!before && after) entries.push({
1220
+ path,
1221
+ type: "added",
1222
+ after
1223
+ });
1224
+ else if (before && !after) entries.push({
1225
+ path,
1226
+ type: "removed",
1227
+ before
1228
+ });
1229
+ else if (before && after && (before.digest !== after.digest || before.type !== after.type || before.size !== after.size || JSON.stringify(before.metadata) !== JSON.stringify(after.metadata))) entries.push({
1230
+ path,
1231
+ type: "modified",
1232
+ before,
1233
+ after
1234
+ });
1235
+ }
1236
+ return {
1237
+ from: from?.id,
1238
+ to: to.id,
1239
+ entries
1240
+ };
1241
+ }
1242
+ async getMeta(key) {
1243
+ return structuredClone((await this.#readMeta()).get(key));
1244
+ }
1245
+ async setMeta(key, value) {
1246
+ await this.#pathLock(this.root, ".vitehub/metadata", async () => {
1247
+ const metadata = new Map(await this.#readMeta());
1248
+ metadata.set(key, value);
1249
+ await this.#writeMeta(metadata);
1250
+ });
1251
+ }
1252
+ async #createSnapshot(name) {
1253
+ const entries = Object.create(null);
1254
+ for (const entry of await this.#list("", { recursive: true }, true)) entries[entry.path] = {
1255
+ type: entry.type,
1256
+ digest: entry.digest,
1257
+ metadata: entry.metadata,
1258
+ size: entry.size
1259
+ };
1260
+ return {
1261
+ id: await sha256({
1262
+ name,
1263
+ entries,
1264
+ createdAt: Date.now()
1265
+ }),
1266
+ name,
1267
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1268
+ entries
1269
+ };
1270
+ }
1271
+ async #readMeta() {
1272
+ const info = await stat(this.#metaPath).catch((error) => {
1273
+ if (error.code === "ENOENT") return void 0;
1274
+ throw error;
1275
+ });
1276
+ if (!info) {
1277
+ this.#metaCache = void 0;
1278
+ return /* @__PURE__ */ new Map();
1279
+ }
1280
+ if (this.#metaCache?.ino === info.ino && this.#metaCache.mtimeMs === info.mtimeMs && this.#metaCache.size === info.size) return this.#metaCache.value;
1281
+ const content = await readFile(this.#metaPath, "utf8").catch((error) => {
1282
+ if (error.code === "ENOENT") return void 0;
1283
+ throw error;
1284
+ });
1285
+ if (!content) {
1286
+ this.#metaCache = {
1287
+ ino: info.ino,
1288
+ mtimeMs: info.mtimeMs,
1289
+ size: info.size,
1290
+ value: /* @__PURE__ */ new Map()
1291
+ };
1292
+ return this.#metaCache.value;
1293
+ }
1294
+ const value = JSON.parse(content);
1295
+ const metadata = !value || Object(value) !== value || Array.isArray(value) ? /* @__PURE__ */ new Map() : new Map(Object.entries(Object(value)));
1296
+ this.#metaCache = {
1297
+ ino: info.ino,
1298
+ mtimeMs: info.mtimeMs,
1299
+ size: info.size,
1300
+ value: metadata
1301
+ };
1302
+ return metadata;
1303
+ }
1304
+ async #writeMeta(metadata) {
1305
+ const { dirname } = await import("node:path");
1306
+ const temp = `${this.#metaPath}.${randomUUID()}.tmp`;
1307
+ await mkdir(dirname(this.#metaPath), { recursive: true });
1308
+ try {
1309
+ await writeFile(temp, JSON.stringify(Object.fromEntries(metadata), null, 2));
1310
+ await rename(temp, this.#metaPath);
1311
+ } catch (error) {
1312
+ await rm(temp, { force: true }).catch(() => void 0);
1313
+ throw error;
1314
+ }
1315
+ }
1316
+ };
1317
+ function createLocalWorkspaceStore(root, options = {}) {
1318
+ if (!root) throw workspaceError("[vitehub] Local workspace store requires a root directory.");
1319
+ if (options.locks !== void 0 && options.locks !== "filesystem" && options.locks !== "process") throw workspaceError("[vitehub] Local workspace store locks must be \"filesystem\" or \"process\".");
1320
+ if (options.ignore !== void 0 && options.ignore !== "git") throw workspaceError("[vitehub] Local workspace store ignore must be \"git\".");
1321
+ return new LocalWorkspaceStore(root, options);
1322
+ }
1323
+ //#endregion
1324
+ //#region src/storage/owned-blob-prefix.ts
1325
+ /**
1326
+ * Returns `_vitehub/<root>`, or `_vitehub/<root>/<prefix>` for a custom prefix.
1327
+ * ViteHub owns every Workspace Blob object, so a custom prefix only nests below the owned root.
1328
+ */
1329
+ function ownedBlobPrefix(root, prefix, label) {
1330
+ if (prefix !== void 0 && !/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(prefix)) throw workspaceError(`[vitehub] ${label} Blob prefix must contain only letters, numbers, underscores, dashes, and single slashes.`);
1331
+ const owned = `${vitehubOwnedPrefix}${root}`;
1332
+ return prefix === void 0 ? owned : `${owned}/${prefix}`;
1333
+ }
1334
+ //#endregion
1335
+ //#region src/storage/provider.ts
1336
+ const MASKED_WORKSPACE_RUNTIME_VALUE = "********";
1337
+ function workspaceRepoName(name) {
1338
+ return name ? name.replace(/[^a-zA-Z0-9_.-]/g, "-") : void 0;
1339
+ }
1340
+ function isWorkspaceStore(value) {
1341
+ if (!value) return false;
1342
+ if (Object.hasOwn(value, "readFile")) return "readFile" in value && typeof value.readFile === "function";
1343
+ let prototype = Object.getPrototypeOf(value);
1344
+ while (prototype && prototype !== Object.prototype) {
1345
+ if (Object.hasOwn(prototype, "readFile")) return Object.hasOwn(prototype, "constructor") && prototype.constructor !== Object && "readFile" in value && typeof value.readFile === "function";
1346
+ prototype = Object.getPrototypeOf(prototype);
1347
+ }
1348
+ return false;
1349
+ }
1350
+ function gitHubWorkspaceOption(value) {
1351
+ return typeof value === "function" ? value : trimmed(value);
1352
+ }
1353
+ function resolveCloudflareArtifactsStore(config = {}, env = process.env) {
1354
+ const repoPrefix = trimmed(config.repoPrefix) ?? readEnv(env, "WORKSPACE_ARTIFACTS_REPO_PREFIX", "VITEHUB_WORKSPACE_ARTIFACTS_REPO_PREFIX") ?? "vitehub-workspace-";
1355
+ const repo = trimmed(config.repo) ?? workspaceRepoName(readEnv(env, "WORKSPACE_ARTIFACTS_REPO", "VITEHUB_WORKSPACE_ARTIFACTS_REPO"));
1356
+ return defu({
1357
+ binding: trimmed(config.binding) ?? readEnv(env, "WORKSPACE_ARTIFACTS_BINDING", "VITEHUB_WORKSPACE_ARTIFACTS_BINDING"),
1358
+ branch: trimmed(config.branch) ?? readEnv(env, "WORKSPACE_ARTIFACTS_BRANCH", "VITEHUB_WORKSPACE_ARTIFACTS_BRANCH"),
1359
+ namespace: trimmed(config.namespace) ?? readEnv(env, "WORKSPACE_ARTIFACTS_NAMESPACE", "VITEHUB_WORKSPACE_ARTIFACTS_NAMESPACE"),
1360
+ repo,
1361
+ repoPrefix
1362
+ }, {
1363
+ binding: "WORKSPACE_ARTIFACTS",
1364
+ namespace: "vitehub",
1365
+ driver: "cloudflare"
1366
+ });
1367
+ }
1368
+ function resolveVercelBlobWorkspaceStore(config = {}, env = process.env) {
1369
+ const prefix = config.prefix ?? readEnv(env, "WORKSPACE_BLOB_PREFIX", "VITEHUB_WORKSPACE_BLOB_PREFIX");
1370
+ ownedBlobPrefix("workspaces", prefix, "Workspace");
1371
+ return {
1372
+ access: config.access ?? "private",
1373
+ ...prefix === void 0 ? {} : { prefix },
1374
+ driver: "vercel",
1375
+ token: MASKED_WORKSPACE_RUNTIME_VALUE
1376
+ };
1377
+ }
1378
+ function resolveGitHubWorkspaceStore(config = {}, env = process.env, input = {}) {
1379
+ const branch = gitHubWorkspaceOption(config.branch) ?? readEnv(env, "VITEHUB_WORKSPACE_GITHUB_BRANCH");
1380
+ const root = config.root === "" ? "" : gitHubWorkspaceOption(config.root) ?? readEnv(env, "VITEHUB_WORKSPACE_GITHUB_ROOT");
1381
+ return {
1382
+ branch: branch ?? (input.runtime ? void 0 : "main"),
1383
+ ...config.database === void 0 ? {} : { database: config.database },
1384
+ driver: "github",
1385
+ ...config.refs ? { refs: { ...config.refs } } : {},
1386
+ repository: gitHubWorkspaceOption(config.repository) ?? gitHubWorkspaceOption(config.repo) ?? readEnv(env, "VITEHUB_WORKSPACE_GITHUB_REPOSITORY"),
1387
+ root: root ?? (input.runtime ? void 0 : ".vitehub/workspaces/<workspace>"),
1388
+ token: input.runtime ? gitHubWorkspaceOption(config.token) ?? readForgeEnv(forgeEnv.github.token, env) ?? "********" : MASKED_WORKSPACE_RUNTIME_VALUE
1389
+ };
1390
+ }
1391
+ function hasVercelWorkspaceBlobEnv(env) {
1392
+ return Boolean(readEnv(env, "BLOB_STORE_ID", "BLOB_READ_WRITE_TOKEN"));
1393
+ }
1394
+ const workspaceStoreDrivers = /* @__PURE__ */ new Set([
1395
+ "cloudflare",
1396
+ "github",
1397
+ "local",
1398
+ "memory",
1399
+ "vercel"
1400
+ ]);
1401
+ /** Driver names that ViteHub renamed to the host name. `npx @vite-hub/codemods driver-key` moves them. */
1402
+ const renamedWorkspaceStoreDrivers = /* @__PURE__ */ new Map([["cloudflare-artifacts", "cloudflare"], ["vercel-blob", "vercel"]]);
1403
+ function normalizeWorkspaceStoreOptions(store, input = {}) {
1404
+ if (isWorkspaceStore(store)) return;
1405
+ if (input.dev && !store) return { driver: "local" };
1406
+ const env = input.env || process.env;
1407
+ const hosting = input.hosting || "";
1408
+ if (store && Object.hasOwn(store, "provider") && store.driver === void 0) {
1409
+ const provider = store.provider;
1410
+ const driver = renamedWorkspaceStoreDrivers.get(String(provider)) ?? provider;
1411
+ throw workspaceErrorDiagnostics.WORKSPACE_RENAMED_STORE_PROVIDER_KEY({
1412
+ driver: JSON.stringify(driver) ?? String(driver),
1413
+ provider: JSON.stringify(provider) ?? String(provider)
1414
+ });
1415
+ }
1416
+ if (store?.driver !== void 0 && !workspaceStoreDrivers.has(store.driver)) throw workspaceErrorDiagnostics.WORKSPACE_UNKNOWN_STORE_DRIVER({
1417
+ driver: JSON.stringify(store.driver),
1418
+ renamed: renamedWorkspaceStoreDrivers.get(String(store.driver))
1419
+ });
1420
+ if (store?.driver === "cloudflare") return resolveCloudflareArtifactsStore(store, env);
1421
+ if (store?.driver === "github") return resolveGitHubWorkspaceStore(store, env, input);
1422
+ if (store?.driver === "memory") return store;
1423
+ if (store?.driver === "vercel") return resolveVercelBlobWorkspaceStore(store, env);
1424
+ if (store?.driver === "local" || store?.root) return defu(store, { driver: "local" });
1425
+ if (store && "driver" in store) throw workspaceError(`[vitehub] Unsupported workspace store driver: ${String(store.driver)}.`);
1426
+ if (hosting.includes("cloudflare")) return { driver: "memory" };
1427
+ if (hasVercelWorkspaceBlobEnv(env)) return resolveVercelBlobWorkspaceStore({}, env);
1428
+ if (hosting.includes("vercel")) return { driver: "memory" };
1429
+ return { driver: "local" };
1430
+ }
1431
+ /** Resolve the effective store once for the runtime and its durability report. */
1432
+ function resolveWorkspaceDefinitionStore(definition, runtimeConfig = getWorkspaceRuntimeConfig(), input = {}) {
1433
+ if (isWorkspaceStore(definition.store)) return definition.store;
1434
+ const rootDir = definition.rootDir || process.cwd();
1435
+ const runtimeStore = runtimeConfig ? runtimeConfig.store : void 0;
1436
+ return normalizeWorkspaceStoreOptions(definition.store || runtimeStore, {
1437
+ env: typeof process !== "undefined" ? process.env : {},
1438
+ hosting: typeof process !== "undefined" ? process.env.VITEHUB_HOST : void 0,
1439
+ rootDir,
1440
+ runtime: true,
1441
+ ...input
1442
+ });
1443
+ }
1444
+ function createWorkspaceStoreFromProvider(definition) {
1445
+ const runtimeConfig = getWorkspaceRuntimeConfig();
1446
+ const store = resolveWorkspaceDefinitionStore(definition, runtimeConfig);
1447
+ if (isWorkspaceStore(store)) return store;
1448
+ const rootDir = definition.rootDir || process.cwd();
1449
+ if (store?.driver === "memory") return createMemoryWorkspaceStore();
1450
+ if (store?.driver === "cloudflare" || store?.driver === "github" || store?.driver === "vercel") {
1451
+ const hostedStore = getWorkspaceHostedStoreLoader()?.(store, definition.name);
1452
+ if (hostedStore) return hostedStore;
1453
+ if (store.driver === "github") return createGitHubWorkspaceStore(store, definition.name);
1454
+ throw workspaceError(`[vitehub] Hosted workspace store "${store.driver}" is not available in this runtime.`);
1455
+ }
1456
+ return createLocalWorkspaceStore(store?.root ? resolve(rootDir, store.root) : runtimeConfig ? resolve(runtimeConfig.root, definition.name) : resolve(rootDir, ".vitehub/workspaces", definition.name), {
1457
+ ignore: store?.ignore,
1458
+ locks: store?.locks
1459
+ });
1460
+ }
1461
+ function isMaskedWorkspaceRuntimeValue(value) {
1462
+ return !value || value === "********";
1463
+ }
1464
+ /**
1465
+ * Uses OIDC when the project has `BLOB_STORE_ID`, like `@vite-hub/blob`. The store then has no
1466
+ * token, so `@vercel/blob` reads the OIDC token itself and falls back to `BLOB_READ_WRITE_TOKEN`.
1467
+ */
1468
+ function resolveRuntimeVercelBlobWorkspaceStore(config, env) {
1469
+ const { token: _maskedToken, ...store } = config;
1470
+ if (readEnv(env, "BLOB_STORE_ID")) return store;
1471
+ const token = readEnv(env, "BLOB_READ_WRITE_TOKEN");
1472
+ if (isMaskedWorkspaceRuntimeValue(token)) throw workspaceErrorDiagnostics.WORKSPACE_R0066({ message: "Missing Vercel Blob credentials for Workspace storage. Connect a Blob store to the Vercel project so it gets `BLOB_STORE_ID`, or set `BLOB_READ_WRITE_TOKEN` off Vercel." });
1473
+ return {
1474
+ ...store,
1475
+ token
1476
+ };
1477
+ }
1478
+ //#endregion
1479
+ export { resolveGitHubWorkspaceStore as a, resolveWorkspaceDefinitionStore as c, setWorkspaceHostedStoreLoader as d, resolveCloudflareArtifactsStore as i, ownedBlobPrefix as l, isWorkspaceStore as n, resolveRuntimeVercelBlobWorkspaceStore as o, normalizeWorkspaceStoreOptions as r, resolveVercelBlobWorkspaceStore as s, createWorkspaceStoreFromProvider as t, getWorkspaceHostedStoreLoader as u };